1. 序列化和反序列化:
定义:
序列化:将对象以字节流的形式保存到磁盘中或者在网络上进行传输;
反序列化:从字节流中解析出对象,但需要有对象的实例;
用法:
序列化:Newtonsoft.Json.JsonConvert.SerializeObject(Readings)
转换前:{ Systolic = {10}, Diastolic = {20}, Pulse = {30} }
转换后:{"Systolic":"10","Diastolic":"20","Pulse":"30"}
反序列化:Newtonsoft.Json.JsonConvert.DeserializeObject(Readings)
public class ReceiveBGEntity { public int Systolic { get; set; } public int Diastolic { get; set; } public int Pulse { get; set; } public override string ToString() { return "Systolic:" + Systolic.ToString() + "; Date:" + Diastolic.ToString() + "; Pulse" + Pulse.ToString(); } } class Program { static void Main(string[] args) { string JSON_BG = "{'Systolic':'1','Diastolic':'5','Pulse':'7'}"; ReceiveBGEntity BG = Newtonsoft.Json.JsonConvert.DeserializeObject<ReceiveBGEntity>(JSON_BG); Console.WriteLine(BG.ToString()); Console.ReadLine(); } }
对于对象序列化和反序列化操作,经常操作的对象有实体对象,集合,DataTale及匿名对象,匿名对象解析方法DeserializeAnonymousType()的使用例子如下所示:
class Program { static void Main(string[] args) { var AnonymousObj = new { ID = 0, Name = string.Empty, Words = string.Empty }; string Results = Newtonsoft.Json.JsonConvert.SerializeObject(AnonymousObj); AnonymousObj = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType("{\"ID\":\"20160427\",\"Name\":\"Tom\",\"Words\":\"Hello are you?\"}", AnonymousObj); Console.WriteLine(AnonymousObj.Name+"["+ AnonymousObj.ID + "],"+ AnonymousObj.Words); Console.ReadLine(); } }