2023.1.5
JavaScriptSerializer
参考实体类:Customer
public class Customer { public int Unid { get; set; } public string CustomerName { get; set; } }
(一)反序列化,用于将对象转换为 JSON 字符串
public string ScriptSerialize(Customer customer) { JavaScriptSerializer js = new JavaScriptSerializer(); return js.Serialize(customer); }
Customer cc = new Customer { Unid = 1, CustomerName = "John" }; string strJson = ScriptSerialize(cc); Console.WriteLine(strJson);
(二)反序列化,将JSON 字符串转换为对象
public Customer ScriptDeserialize(string strJson) { JavaScriptSerializer js = new JavaScriptSerializer(); return js.Deserialize<Customer>(strJson); }
Customer c1 = ScriptDeserialize(strJson); Console.WriteLine(c1.Unid + " " + c1.CustomerName);
(三)方法泛型
public string ScriptSerialize<T>(T t) { JavaScriptSerializer js = new JavaScriptSerializer(); return js.Serialize(t); } public T ScriptDeserialize<T>(string strJson) { JavaScriptSerializer js = new JavaScriptSerializer(); return js.Deserialize<T>(strJson); }
Customer cc = new Customer { Unid = 1, CustomerName = "John" }; string strJson = ScriptSerialize<Customer>(cc); Console.WriteLine(strJson); Customer c1 = ScriptDeserialize<Customer>(strJson); Console.WriteLine(c1.Unid + " " + c1.CustomerName);
JsonConvert
public class Person { /// <summary> /// 名称 /// </summary> public string pName; /// <summary> /// 年龄 /// </summary> public int pAge; /// <summary> /// 性别 /// </summary> public string pSex; }
// 声明一个Person对象,并赋值 Person p1 = new Person(); p1.pName = "张三"; p1.pAge = 18; p1.pSex = "男"; // 输出类型 Console.WriteLine("输出p1类型:{0}" + "\n",p1.GetType()); // 转换成JSON字符串 var str = JsonConvert.SerializeObject(p1); Console.WriteLine("输出转换后的值:{0}" + "\n" + "转换后的类型:{1} " + "\n", str,str.GetType()); // 使用反序列化到指定Person类型 var pStr = JsonConvert.DeserializeObject<Person>(str); Console.WriteLine("接受后的Name:{0}" + "\n" + "反序列后的类型:{1} " + "\n", pStr.pName, pStr.GetType()); Console.ReadKey();
标签:Customer,Console,string,C#,strJson,与非,JavaScriptSerializer,序列化,public From: https://www.cnblogs.com/kezhang/p/17027748.html