json string 与object 之间的转化

1.将json string转化成object

   1:  public static T GetObjectFromJson<T>(string jsonString)
   2:  {
   3:      DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
   4:      MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
   5:      var obj = (T)serializer.ReadObject(stream);
   6:      stream.Close();
   7:      return obj;
   8:  }
 
 

2.将obect转化成json string

   1:  public static string GetJsonFromObject<T>(T obj)
   2:  {
   3:      DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(T));
   4:      using (MemoryStream ms = new MemoryStream())
   5:      {
   6:          json.WriteObject(ms, obj);
   7:          string szJson = Encoding.UTF8.GetString(ms.ToArray());
   8:          return szJson;
   9:      }
  10:  }

注意,定义的对象T一定要和json 字符串一一对应

e.g: json string {\"ID\":1,\"Items\":[{\"Name\":\"22\"},{\"Name\":\"23\"}]}

定义的对象就必须是:

   1:  [DataContract]
   2:  class Demo
   3:  {
      [DataMember]
   4:      public int ID { get; set; }
   5:      [DataMember]
   6:      public List<Student> Items { get; set; }
   7:  }
   8:   
   9:  [DataContract]
  10:  class Student
  11:  {
  12:      [DataMember]
  13:      public string Name { get; set; }
  14:  }

其中T就是Demo 这个类

使用:

   1:   string json = "{\"ID\":1,\"Items\":[{\"Name\":\"22\"},{\"Name\":\"23\"}]}";
   2:   Demo obj = GetObjectFromJson<Demo>(json);

上一篇:[python基础]关于中文编码和解码那点事儿


下一篇:【C语言教程】“双向循环链表”学习总结和C语言代码实现!