首页 > 代码库 > C#读写Json

C#读写Json

  C#处理json文件主要有两种方式:

  (1)使用JavaScriptSerializer类,需要引入System.Web.Extension库,并添加下面两个引用:

  using System.Web;
  using System.Web.Script.Serialization;

  主要代码如下所示:

    public class Data    {        public int Id { get; set; }        // [ScriptIgnore]        public string Name { get; set; }        public string GetName()        {            return Id.ToString() + Name;        }    }    public class JsonPaserWeb    {        // Object->Json        public string Serialize(Data obj)        {            JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();            string json = jsonSerializer.Serialize(obj);            return json;        }        // Json->Object        public Data Deserialize(string json)        {            JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();            //执行反序列化            Data obj = jsonSerializer.Deserialize<Data>(json);            return obj;        }    }

  可以使用[ScriptIgnore]标记来让某个变量不参与序列化。

  (2)使用DataContractJsonSerializer类,需要引入System.Runtime.Serialization库,并加入如下引用:

  using System.Runtime.Serialization;
  using System.Runtime.Serialization.Json;

  示例代码如下所示:

  [DataContract]    public class Data    {        [DataMember(Name = "id", Order = 0)]        public int Id;        [DataMember(Name = "name", Order = 1)]        public string Name;        [DataMember(Name = "child", Order = 2)]        public Child child = new Child();        [DataMember(Name = "list", Order = 3)]        public List<int> Ids = new List<int>();        [DataMember(Name = "dictionary", Order = 4)]        public Dictionary<int, Child> dic = new Dictionary<int, Child>();        [IgnoreDataMember]        public string Description = "This is a json data class";    }    public class Child    {        public float Age;        public string FullName;    }    class JsonParserRuntime    {        // Object->Json        public string Serialize(Data obj)        {            DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(obj.GetType());            string json = "";            using (MemoryStream stream = new MemoryStream())            {                jsonSerializer.WriteObject(stream, obj);                json = Encoding.UTF8.GetString(stream.ToArray());            }            return json;        }        // Json->Object        public Data Deserialize(string json)        {            Data obj = null;            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))            {                DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(Data));                obj = (Data)jsonSerializer.ReadObject(ms);            }            return obj;        }    }

  使用[DataContract]标记的类,可以同时使用[DataMember(Name = "id", Order = 0)]标记来处理变量,也可以使用[IgnoreDataMember]标记来让某个变量不参与序列化。

C#读写Json