zoukankan      html  css  js  c++  java
  • 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);
  • 相关阅读:
    CentOS6.5配置MySQL主从同步
    CentOS6.5安装telnet
    linux 下安装Google Chrome (ubuntu 12.04)
    jdk w7环境变量配置
    JDBCConnectionException: could not execute query,数据库连接池问题
    注意开发软件的版本问题!
    linux mysql命令行导入导出.sql文件 (ubuntu 12.04)
    linux 下root用户和user用户的相互切换 (ubuntu 12.04)
    linux 下 vim 的使用 (ubuntu 12.04)
    linux 下安装配置tomcat-7 (ubuntu 12.04)
  • 原文地址:https://www.cnblogs.com/lavenvsxiaoye/p/3525396.html
Copyright © 2011-2022 走看看