JSON.NET(http://json.codeplex.com/)使用来将.NET中的对象转换为JSON字符串(序列化?),或者将JSON字符串转换为.NET中已有类型的对象(反序列化?)
首先为了例子随便定义一个类型:
public class Product { string Name { get; set; } public DateTime Expiry { decimal Price { string[] Sizes { set; } override string ToString() { return string.Format(@H_502_51@"@H_502_51@Name:{0},Expiry:{1},Price:{2},SizesCount:{3}@H_502_51@",Name,Expiry,Price,Sizes.Length); } }
初始化对象:
static void Main(string[] passwordargs)
{
Product product = new Product()
{
Name = @H_502_51@android DateTime.Now,Price = 2000,Sizes = new string[] { @H_502_51@1.5@H_502_51@",@H_502_51@2.2@H_502_51@4.1@H_502_51@" }
};
}
进行到JSON的转换:
Console.WriteLine(JsonConvert.SerializeObject(product));
输出结果:
{"Name":"android","Expiry":"2013-08-30T09:50:11.5147845+08:00","Price":2000.0,"Sizes":["1.5","2.2","4.1"]}
其它看起来一切正常,除了这个日期有点怪
格式化日期:
//设置日期时间的格式,与DataTime类型的ToString格式相同 IsoDateTimeConverter iso = new IsoDateTimeConverter(); iso.DateTimeFormat = @H_502_51@yyyy-MM-dd HH:mm:ss@H_502_51@"; Console.WriteLine(JsonConvert.SerializeObject(product,iso));
输出结果:
{"Name":"android","Expiry":"2013-08-30 09:53:58","4.1"]}
从JSON到对象的转换:
string str = @H_502_51@{\"Name\":\"android\",\"Expiry\":\"2013-08-30 09:53:58\",\"Price\":2000.0,\"Sizes\":[\"1.5\",\"2.2\",\"4.1\"]}@H_502_51@";
Product p = (Product)JsonConvert.DeserializeObject(str,typeof(Product));
Console.WriteLine(p.ToString());
输出结果:
Name:android,Expiry:2013/8/30 9:53:58,Price:2000.0,SizesCount:3
从JSON到键值对的转换:
string strJson = @H_502_51@@"@H_502_51@{""Name1"": ""小明"",""Name2"": ""小花"",""Name3"": ""小红""}@H_502_51@";
Dictionary<string,255)">string> _dictionary = JsonConvert.DeserializeObject<Dictionary<string>>(strJson);
foreach (KeyValuePair<string> kp in _dictionary)
{
Console.WriteLine(kp.Key + @H_502_51@:@H_502_51@" + kp.Value);
}
输出结果:
Name1:小明
Name2:小花
Name3:小红
从字符串转换到JSON对象,以及JSON对象的简单使用:
string strJson2 = @H_502_51@{ ""student"": { ""Name1"": ""小明"",""Name3"": ""小红""} }@H_502_51@";
JObject jsonObj = JObject.Parse(strJson2);
Console.WriteLine(jsonObj[@H_502_51@student@H_502_51@"][@H_502_51@Name1@H_502_51@"].ToString());
Console.WriteLine(jsonObj[@H_502_51@Name2@H_502_51@Name3@H_502_51@"].ToString());
输出结果:
小明
小花
小红
直接生成JSON对象:
JObject json = new JObject( new JProperty(@H_502_51@Channelnew JObject( title@H_502_51@JSON@H_502_51@"),0)">link@H_502_51@JSON.NET@H_502_51@description@H_502_51@JSON.NET Description@H_502_51@itemsnew JArray( new JObject(haha1@H_502_51@123@H_502_51@")),0)">haha2@H_502_51@456@H_502_51@haha3@H_502_51@789@H_502_51@")) ))))); Console.WriteLine(json.ToString());
输出结果:
{
"Channel": {
"title": "JSON",
"link": "JSON.NET",
"description": "JSON.NET Description",
"items": [
{
"haha1": "123"
},
{
"haha2": "456"
},
{
"haha3": "789"
}
]
}
}
暂时先记录这么多,以后再继续补充