C#中实体转Json常用的类JavaScriptSerializer,该类位于using System.Web.Script.Serialization;命名空间中,添加引用system.web.extensions。常见序列化和反序列化的方法如下:
public static List<T> JSONStringToList<T>(this string JsonStr) { JavaScriptSerializer Serializer = new JavaScriptSerializer(); List<T> objs = Serializer.Deserialize<List<T>>(JsonStr); return objs; } public static T Deserialize<T>(string json) { T obj = Activator.CreateInstance<T>(); using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json))) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType()); return (T)serializer.ReadObject(ms); } }
C#中实体转JSON常用的实例情况:
第一种JSON格式:
{"Name":"苹果","Price":5.5}
该类型的json,对应的实体就是一个类,里面两个属性name和price,对应如下:
public class Product { public string Name { get; set; } public double Price { get; set; } }
第二种JSON格式:
{"GetProducts":[{"Name":"苹果","Price":5.5},{"Name":"橘子","Price":2.5},{"Name":"柿子","Price":16}]}
对应的类封装如下:
public class Product { public string Name { get; set; } public double Price { get; set; } } public class ProductList { public List<Product> GetProducts { get; set; } }
封装的时候,只需要封装ProductList实例;
第三种:
{"GetProducts":["5841526","985423","23366368"]}
这种json对应的C#类如下:
public class ProductList { public List<string> GetProductsname=new List<string>( ){"5841526","985423","23366368"}; }
第四种:
{"GetProducts":[{"Name":"5841526"},{"Price",985423}]}
这种json有点难度,但是我们c#也能转化,对应的C#类如下:
public class Product { public string Name { get; set; } } public class Pnum { public double Price { get; set; } } public class ProductList { public List<object> GetProducts { get; set; } } public static string GetJsonString() { List<object> products = new List<object>() { new Product(){Name="苹果"}, new Pnum(){ Price=3.2} }; ProductList pl = new ProductList() { GetProducts = products }; return new JavaScriptSerializer().Serialize(pl); }
这就是我总结的常见四种json对应的序列化方式。JavaScriptSerializer是一款不错的json序列化的工具,用好了就是神器,晚安!