1. 程式人生 > >JSON序列化與反序列化

JSON序列化與反序列化

class a using demo pos define sys ali convert lose

1.add reference [System.Runtime.Serializatio]

2.using [System.Runtime.Serialization] and [System.Runtime.Serialization.Json]

3.define model class add [DataContract] and [DataMember] attribute

class Demo
{
    [DataMember]
    public int ID { get; set; }
    [DataMember]
    public string Name { get
; set; } [DataMember] public int Age { get; set; } }

4.convert code

DataContractJsonSerializer jsonSer = new DataContractJsonSerializer(typeof(Demo));
            
//json to model
string strJson = "{\"ID\":3,\"Name\":\"TestName\",\"Age\":100}";
Stream ms1 = new MemoryStream(Encoding.Default.GetBytes(strJson));
Demo item1 
= (Demo)jsonSer.ReadObject(ms1); ms1.Close(); //model to json Demo item2 = new Demo { ID = 1, Name = "TestName", Age = 12 }; Stream ms2 = new MemoryStream(); jsonSer.WriteObject(ms2, item2); byte[] arr = new byte[ms2.Length]; ms2.Position = 0; ms2.Read(arr, 0, arr.Length); ms2.Close(); Console.WriteLine(Encoding.Default.GetString(arr));

JSON序列化與反序列化