zoukankan      html  css  js  c++  java
  • C#中 JSON 序列化 与 反序列化

    JSON 字符串用途广泛,不单单用在Javascript里面,在C# ,PHP ,JAVA 等开发语言也会用到,经常需要把对象序列化为JSON字符串或把JSON字符串反序列化为对象实例;

    以下是C#中序列化和反序列化的例子;

    首先需要引用命名空间:

    using System.Runtime.Serialization.Json;

    把对象序列化成字符串:

    public string Serialize<T>(T obj)
    {
      DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
      using (MemoryStream stream1 = new MemoryStream())
      {
        ser.WriteObject(stream1, obj);
        stream1.Position = 0;
        StreamReader sr = new StreamReader(stream1);
        //Console.WriteLine("JSON form of {0} object",typeof(T));
        return sr.ReadToEnd();
      }
    }

    反序列化对象

            public T Deserialize<T>(string json) where T :  class
            {
           
                MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json));
                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
                T deserializedObj = ser.ReadObject(ms) as T;
                ms.Close();
                return deserializedObj; 
            }
  • 相关阅读:
    手机截屏雷阵雨
    2010年5月20日 用户的数据永远不会靠谱
    2010年5月17日 OCD
    2010年8月9日 流水账
    2010年5月19日 借鉴
    立表为据
    2010年6月2日 回来
    不重视小C打屁屁
    2010年8月16日 知行合一
    2010年5月18日 小细节大隐患
  • 原文地址:https://www.cnblogs.com/tcli/p/9085249.html
Copyright © 2011-2022 走看看