zoukankan      html  css  js  c++  java
  • .NET Oject And Json

      在最近的项目开发中,需要将.NET 对象序列化为Json字符串,传递到客户端浏览器,同时,需要将客户端的Json字符串传递到Server,反序列化为.NET对象,主要有三种方式:

    •   DataContractJsonSerializer

      序列化:

    /// <summary>
    /// 将.NET对象序列化为Json
    /// </summary>
    /// <typeparam name="T">.NET对象类型,此处为泛型</typeparam>
    /// <param name="obj">.NET对象</param>
    /// <returns>返回Json字符串</returns>
    public static string Serialize<T>(T obj)
    {
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
    MemoryStream ms = new MemoryStream();
    serializer.WriteObject(ms, obj);
    string returnString = Encoding.UTF8.GetString(ms.ToArray());
    return returnString;
    }

      反序列化:

    /// <summary>
    /// 将Json反序列化为.NET对象
    /// </summary>
    /// <typeparam name="T">.NET对象类型</typeparam>
    /// <param name="json">序列化字符串</param>
    /// <returns>返回.NET对象</returns>
    public static T Deserialize<T>(string json)
    {
    T obj = Activator.CreateInstance<T>();
    MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
    obj = (T)serializer.ReadObject(ms);
    ms.Close();
    return obj;
    }
    • JavaScriptSerializer

      序列化:

     /// <summary>
    /// 将.NET对象序列化为Json
    /// </summary>
    /// <typeparam name="T">.NET对象类型,此处为泛型</typeparam>
    /// <param name="obj">.NET对象</param>
    /// <returns>返回Json字符串</returns>
    public static string Serialize<T>(T obj)
    {
    System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    return serializer.Serialize(obj);
    }

      反序列化:

     /// <summary>
    /// 将Json反序列化为.NET对象
    /// </summary>
    /// <typeparam name="T">.NET对象类型</typeparam>
    /// <param name="json">序列化字符串</param>
    /// <returns>返回.NET对象</returns>
    public static T DeSerialize1<T>(string json)
    {
    System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    return serializer.Deserialize<T>(json);
    }

      我还是比较喜欢使用JavaScriptSerializer

    • Json.NET

      以后使用此库,再写如何使用Json.NET如何操作Json



     

  • 相关阅读:
    类的有参方法
    WPF 中的设备无关单位
    Skelta BPM.NET 2006 初探
    Reporting Services Handscript
    C语言I博客作业03
    C语言I博客作业02
    C++类的运算符重载和转换函数结合的问题
    C++ 函数返回类成员的问题
    kaggle 利用linear regression 进行房价预测
    android Could not open: c:\。。。。\.android/avd/XXXX.ini 问题和解决方法
  • 原文地址:https://www.cnblogs.com/PerfectSoft/p/2430562.html
Copyright © 2011-2022 走看看