Json.Net 学习笔记(一)

使用Newtonsoft.Json进行JSON序列化与反序列化
本文详细介绍了如何使用Newtonsoft.Json库进行JSON数据的序列化与反序列化操作,包括下载库、定义类、序列化与反序列化过程,并解释了JsonProperty和TypeNameHandling属性的作用。

使用Newtonsoft.Json这是一个开源的Json.Net库。

下载地址:http://json.codeplex.com/releases/view/50552。当前版本为 Release 8

从下载到的源代码中获取Newtonsoft.Json.Net20.dll,添加到自己的工程中。

using Newtonsoft.Json;

定义类:

 public class Message
    {
        public string Address { get; set; }
        [JsonProperty(TypeNameHandling = TypeNameHandling.All)]
        public object Body { get; set; }
    }
    public class SearchDetails
    {
        public string Query { get; set; }
        public string Language { get; set; }
    }

测试:

           Message message = new Message
            {
                Address = "http://google.com/",
                Body = new SearchDetails { Query = "Json.Net", Language = "en-us" }
            };
            string jsonMsg = JsonConvert.SerializeObject(message, Formatting.Indented);//Indented表示以缩进形式显示结果
            System.Diagnostics.Debug.Write(jsonMsg);
            Message deserialized = JsonConvert.DeserializeObject<Message>(jsonMsg);
            SearchDetails searchDetails = (SearchDetails)deserialized.Body;
            Response.Write(searchDetails.Query + "," + searchDetails.Language + "<br/>");

Debug输出结果格式:

{
  "Address": "http://google.com/",
  "Body": {
    "$type": "TestJsonSerialization.SearchDetails, TestJsonSerialization",
    "Query": "Json.Net",
    "Language": "en-us"
  }
}

注:1.JsonProperty标记字段或属性,用来控制它作为一个Json对象的属性序列化。

       2.TypeNameHandling 用来为Json序列化指定类型名。它有几个枚举值:

MemberDescription
NoneDo not include the .NET type name when serializing types. 
ObjectsInclude the .NET type name when serializing into a JSON object structure. 
ArraysInclude the .NET type name when serializing into a JSON array structure. 
AutoInclude the .NET type name when the type of the object being serialized is not the same as its declared type. 
AllAlways include the .NET type name when serializing. 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值