本文主要是介绍C# Newtonsoft.Json使用等价模型高效自定义序列化,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
有一些对象序列化不能自动序化,或者序列化后Json过于臃肿,就得自定义序列化。
一般实现了ISerializable接口的类的对象都可以自动序列化。如Bitmap。
下面演示一种使用等价模型(相对等价)的方法来自定义序列化,核心思想:在序列化时用一个新对象替换原始对象,反序列化时替换回原对象。
先定义接口:
/// <summary>/// </summary>/// <typeparam name="Origin">原始对象</typeparam>/// <typeparam name="Model">对应模型</typeparam>internal interface IWrapConverter<Origin,Model>where Model:new(){void GetDataFrom(Origin origin);void SetDataTo(Origin origin);}
序列化反序列化转化器
internal class WrapConverter<Origin, Model> : JsonConverter where Model :IWrapConverter<Origin, Model>,new(){public override bool CanConvert(Type objectType){//如果不使用JsonSerializerSettings 不必实现?throw new NotImplementedException();}public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer){ if(existingValue is Origin origin){var model= serializer.Deserialize<Model>(reader);model.SetDataTo(origin);} return existingValue;}public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer){if(value is Origin origin){var model = new Model();model.GetDataFrom(origin);serializer.Serialize(writer, model);}}}
编写对应模型类,属性必须是public
internal class PenModel:IWrapConverter<Pen,PenModel>{public float Width { set; get; }public Color Color { set; get; }public void GetDataFrom(Pen pen){Width = pen.Width;Color = pen.Color; }public void SetDataTo(Pen origin){origin.Color=Color;origin.Width=Width;}}
internal class BitmapModel : IWrapConverter<Bitmap, BitmapModel>{public byte[] Data { set; get; }public void GetDataFrom(Bitmap origin){using(var ms=new MemoryStream()){origin.Save(ms, ImageFormat.Png);Data = ms.ToArray();}}public void SetDataTo(Bitmap origin){using (var ms = new MemoryStream(Data)){var bitmap = new Bitmap(ms);using(var g = Graphics.FromImage(origin)){g.DrawImage(bitmap, new Rectangle(0, 0, origin.Width, origin.Height),new Rectangle(0,0,bitmap.Width,bitmap.Height),GraphicsUnit.Pixel);}}}}
被序列化的对象
internal class Path{public List<Point> Points { set; get; } = new List<Point>();public bool End { get; set; } = false;[JsonConverter(typeof(WrapConverter<Pen, PenModel>))]public Pen Pen { get; private set; } = new Pen(Color.White);public long Time { get; set; }[JsonConverter(typeof(WrapConverter<Bitmap, BitmapModel>))]public Bitmap Bitmap { get; set; }//创建对象时必须对所有属性初始化即非Null,否则该属性反序列化失败,为空public Path(){Bitmap = new Bitmap(100, 100);}public void Init(){var rand = new Random();for (int i = 0; i < 10; i++){var point = new Point(rand.Next(100), rand.Next(100));Points.Add(point);}End = rand.Next(2) > 0;Pen = Pens.Red;Time = DateTime.Now.Ticks;using (var g = Graphics.FromImage(Bitmap)){g.Clear(Color.White);g.DrawLine(Pen, 0, 0, 100, 100);}}}
测试
private void button1_Click(object sender, EventArgs e){var path = new Path();path.Init();var json = JsonConvert.SerializeObject(path);Debug.WriteLine(json);path=JsonConvert.DeserializeObject<Path>(json);Debug.WriteLine(path.Pen.Color);path.Bitmap?.Save("123.png");}
输出
{"Points":["78, 53","42, 39","78, 13","1, 14","32, 44","47, 63","92, 78","12, 13","35, 98","4, 18"],"End":true,"Pen":{"Width":1.0,"Color":"Red"},"Time":638117064135963028,"Bitmap":{"Data":"iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAH6SURBVHhe7dJJdsQgEARR3f/S7YfdtnuShKBmIjasKz/bbdtuFKcfDVDC9C8BSoieFUBx710AFNc+rw+KW/vLg+LS8eqgmHe+OCim9a0Niln9S4Ni0rWVQVHv+sKgqDa2LihqjS8Likpzq4Ii3vyioIgmsyYoYsktCYpIsiuCMp38gqBMpbMeKMPpLQfKULqrgXI5/cVAuZTNWqB0Z7cUKF3ZrgTKafYLgXKYzzqg7Oa3DCgf810FlLf8FwHlqRhrgPJXnCVA+S7WCqAEA2ktjhLz+oVR4l6+KErsqxdEiX/xYig5rl0IJc+li6DkunIBlHwXFkfJeV1hlLyXFUXJfVVBlPwXFUOpcU0hlEKXFPlb97dGBVBqgbSSo9QDaSVGqQnSSopSF6SVEKU2SCsZSn2QViKUNUBaSVDWAWklQFkLpBUcZT2QVmCUNUFaQVHWBWkFRFkbpBUMBZBWIBRAfguCAshjAVAAec0ZBZBPOaIAspcTCiBHOaAAcpYxCiA9GaIA0psRCiBXMkAB5GrKKICMpIgCyGhKKIDMpIACyGzCKIBIJIgCiFRCKIBIJoACiHSTKIBoNIECiFaDKIBoNoACiHYXUQCx6AIKIFZ1ogBiWQcKINadoADi0QEKIF7toADi2QcUQLx7QQEkQg8ogETpjgJIpLbt9gWF0eWPpI95/AAAAABJRU5ErkJggg=="}}
Color [Red]
图片
总结
这是一点个人总结,如果该类有属性在执行构造方法后无初始化怎么办?
提示:一个方法是继承该类在构造方法给该属性初始化,再序列化子类即可。
这篇关于C# Newtonsoft.Json使用等价模型高效自定义序列化的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!