JSON.NET(http://json.codeplex.com/)使用来将.NET中的对象转换为JSON字符串(序列化?),或者将JSON字符串转换为.NET中已有类型的对象(反序列化?)
首先为了例子随便定义一个类型:
public
class
Product{
public
string Name {
get;
set
; }
public DateTime Expiry {
get;
set
; }
public
decimal Price {
get;
set
; }
public
string[] Sizes {
get;
set
; }
public
override
string
ToString() {
return
string.Format(
"
Name:{0},Expiry:{1},Price:{2},SizesCount:{3}
"
, Name, Expiry, Price, Sizes.Length); }}
初始化对象:
public
static
void Main(
string
[] passwordargs){ Product product =
new
Product() { Name =
"
android
"
, Expiry =
DateTime.Now, Price =
2000
, Sizes =
new
string[] {
"
1.5
",
"
2.2
",
"
4.1
"
} };}
进行到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 =
"
yyyy-MM-dd HH:mm:ss
"
;Console.WriteLine(JsonConvert.SerializeObject(product, iso));
输出结果:
{"Name":"android","Expiry":"2013-08-30 09:53:58","Price":2000.0,"Sizes":["1.5","2.2","4.1"]}
从JSON到对象的转换:
string str =
"
{\"Name\":\"android\",\"Expiry\":\"2013-08-30 09:53:58\",\"Price\":2000.0,\"Sizes\":[\"1.5\",\"2.2\",\"4.1\"]}
"
;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 =
@"
{""Name1"": ""小明"",""Name2"": ""小花"",""Name3"": ""小红""}
"
;Dictionary<
string,
string> _dictionary = JsonConvert.DeserializeObject
string,
string>>
(strJson);
foreach(KeyValuePair<
string,
string> kp
in
_dictionary){ Console.WriteLine(kp.Key +
"
:
" +
kp.Value);}
输出结果:
Name1:小明
Name2:小花
Name3:小红
从字符串转换到JSON对象,以及JSON对象的简单使用:
string strJson2 =
@"
{ ""student"": { ""Name1"": ""小明"" , ""Name2"": ""小花"" , ""Name3"": ""小红""} }
"
;JObject jsonObj =
JObject.Parse(strJson2);Console.WriteLine(jsonObj[
"
student
"][
"
Name1
"
].ToString());Console.WriteLine(jsonObj[
"
student
"][
"
Name2
"
].ToString());Console.WriteLine(jsonObj[
"
student
"][
"
Name3
"].ToString());
输出结果:
小明
小花
小红
直接生成JSON对象:
JObject json =
new
JObject(
new JProperty(
"
Channel
"
,
new
JObject(
new JProperty(
"
title
",
"
JSON
"
),
newJProperty(
"
link
",
"
JSON.NET
"
),
new JProperty(
"
description
",
"
JSON.NET Description
"
),
new JProperty(
"
items
"
,
new
JArray(
new JObject(
new JProperty(
"
haha1
",
"
123
"
)),
new JObject(
new JProperty(
"
haha2
",
"
456
"
)),
newJObject(
new JProperty(
"
haha3
",
"
789
"
)) )))));Console.WriteLine(json.ToString());
输出结果:
{
"Channel": {
"title": "JSON",
"link": "JSON.NET",
"description": "JSON.NET Description",
"items": [
{
"haha1": "123"
},
{
"haha2": "456"
},
{
"haha3": "789"
}
]
}
}
======================================
一.Linq to JSON是用来干什么的?
Linq to JSON是用来操作JSON对象的.可以用于快速查询,修改和创建JSON对象.当JSON对象内容比较复杂,而我们仅仅需要其中的一小部分数据时,可以考虑使用Linq to JSON来读取和修改部分的数据而非反序列化全部.
二.创建JSON数组和对象
在进行Linq to JSON之前,首先要了解一下用于操作Linq to JSON的类.
类名 |
说明 |
JObject |
用于操作JSON对象 |
JArray |
用语操作JSON数组 |
JValue |
表示数组中的值 |
JProperty |
表示对象中的属性,以"key/value"形式 |
JToken |
用于存放Linq to JSON查询后的结果 |
1.创建JSON对象
JObject staff =
new
JObject(); staff.Add(
new JProperty(
"
Name
",
"
Jack
"
)); staff.Add(
new JProperty(
"
Age
",
33
)); staff.Add(
newJProperty(
"
Department
",
"
Personnel Department
"
)); staff.Add(
newJProperty(
"
Leader
",
new JObject(
new JProperty(
"
Name
",
"
Tom
"),
new JProperty(
"
Age
",
44),
new JProperty(
"
Department
",
"
Personnel Department
"
)))); Console.WriteLine(staff.ToString());
结果:
除此之外,还可以通过一下方式来获取JObject.JArray类似。
方法 |
说明 |
JObject.Parse(string json) |
json含有JSON对象的字符串,返回为JObject对象 |
JObject.FromObject(object o) |
o为要转化的对象,返回一个JObject对象 |
JObject.Load(JsonReader reader) |
reader包含着JSON对象的内容,返回一个JObject对象 |
2.创建JSON数组
JArray arr =
new
JArray(); arr.Add(
new JValue(
1
)); arr.Add(
new JValue(
2
)); arr.Add(
new JValue(
3
)); Console.WriteLine(arr.ToString());
结果:
三.使用Linq to JSON
1.查询
首先准备Json字符串,是一个包含员工基本信息的Json
string json =
"
{\"Name\" : \"Jack\", \"Age\" : 34, \"Colleagues\" : [{\"Name\" : \"Tom\" , \"Age\":44},{\"Name\" : \"Abel\",\"Age\":29}] }
";
①获取该员工的姓名
//
将json转换为JObject JObject jObj =
JObject.Parse(json);
//
通过属性名或者索引来访问,仅仅是自己的属性名,而不是所有的 JToken ageToken = jObj[
"
Age
"
]; Console.WriteLine(ageToken.ToString());
结果:
②获取该员工同事的所有姓名
//
将json转换为JObject JObject jObj =
JObject.Parse(json);
var names=
from staff
in jObj[
"
Colleagues
"
].Children()
select (
string)staff[
"
Name
"
];
foreach (
var name
in
names) Console.WriteLine(name);
"Children()"可以返回所有数组中的对象
结果:
2.修改
①现在我们发现获取的json字符串中Jack的年龄应该为35
//
将json转换为JObject JObject jObj =
JObject.Parse(json); jObj[
"
Age
"] =
35
; Console.WriteLine(jObj.ToString());
结果:
注意不要通过以下方式来修改:
JObject jObj =
JObject.Parse(json); JToken age = jObj[
"
Age
"
]; age =
35;
②现在我们发现Jack的同事Tom的年龄错了,应该为45
//
将json转换为JObject JObject jObj =
JObject.Parse(json); JToken colleagues = jObj[
"
Colleagues
"
]; colleagues[
0][
"
Age
"] =
45
; jObj[
"
Colleagues
"] =
colleagues;//修改后,再赋给对象 Console.WriteLine(jObj.ToString());
结果:
3.删除
①现在我们想删除Jack的同事
JObject jObj =
JObject.Parse(json); jObj.Remove(
"
Colleagues
"
);//跟的是属性名称 Console.WriteLine(jObj.ToString());
结果:
②现在我们发现Abel不是Jack的同事,要求从中删除
JObject jObj =
JObject.Parse(json); jObj[
"
Colleagues
"][
1
].Remove(); Console.WriteLine(jObj.ToString());
结果:
4.添加
①我们发现Jack的信息中少了部门信息,要求我们必须添加在Age的后面
//
将json转换为JObject JObject jObj =
JObject.Parse(json); jObj[
"
Age
"].Parent.AddAfterSelf(
newJProperty(
"
Department
",
"
Personnel Department
"
)); Console.WriteLine(jObj.ToString());
结果:
②现在我们又发现,Jack公司来了一个新同事Linda
//
将json转换为JObject JObject jObj =
JObject.Parse(json); JObject linda =
new JObject(
new JProperty(
"
Name
",
"
Linda
"),
new JProperty(
"
Age
",
"
23
"
)); jObj[
"
Colleagues
"
].Last.AddAfterSelf(linda); Console.WriteLine(jObj.ToString());
结果:
四.简化查询语句
使用函数SelectToken可以简化查询语句,具体:
①利用SelectToken来查询名称
JObject jObj =
JObject.Parse(json); JToken name = jObj.SelectToken(
"
Name
"
); Console.WriteLine(name.ToString());
结果:
②利用SelectToken来查询所有同事的名字
JObject jObj =
JObject.Parse(json);
var names = jObj.SelectToken(
"
Colleagues
").Select(p => p[
"
Name
"
]).ToList();
foreach (
var name
in
names) Console.WriteLine(name.ToString());
结果:
③查询最后一名同事的年龄
//
将json转换为JObject JObject jObj =
JObject.Parse(json);
var age = jObj.SelectToken(
"
Colleagues[1].Age
"
); Console.WriteLine(age.ToString());
结果:
FAQ
1.如果Json中的Key是变化的但是结构不变,如何获取所要的内容?
例如:
1
{
2
"
trends
"
:
3
{
4
"
2013-05-31 14:31
"
:
5
[
6 {
"
name
":
"
我不是谁的偶像
"
,
7
"
query
":
"
我不是谁的偶像
"
,
8
"
amount
":
"
65172
"
,
9
"
delta
":
"
1596
"
},
10 {
"
name
":
"
世界无烟日
",
"
query
":
"
世界无烟日
",
"
amount
":
"
33548
",
"
delta
":
"
1105
"
},
11 {
"
name
":
"
最萌身高差
",
"
query
":
"
最萌身高差
",
"
amount
":
"
32089
",
"
delta
":
"
1069
"
},
12 {
"
name
":
"
中国合伙人
",
"
query
":
"
中国合伙人
",
"
amount
":
"
25634
",
"
delta
":
"
2
"
},
13 {
"
name
":
"
exo回归
",
"
query
":
"
exo回归
",
"
amount
":
"
23275
",
"
delta
":
"
321
"
},
14{
"
name
":
"
新一吻定情
",
"
query
":
"
新一吻定情
",
"
amount
":
"
21506
",
"
delta
":
"
283
"
},
15 {
"
name
":
"
进击的巨人
",
"
query
":
"
进击的巨人
",
"
amount
":
"
20358
",
"
delta
":
"
46
"
},
16 {
"
name
":
"
谁的青春没缺失
",
"
query
":
"
谁的青春没缺失
",
"
amount
":
"
17441
",
"
delta
":
"
581
"
},
17 {
"
name
":
"
我爱幸运七
",
"
query
":
"
我爱幸运七
",
"
amount
":
"
15051
",
"
delta
":
"
255
"
},
18 {
"
name
":
"
母爱10平方
",
"
query
":
"
母爱10平方
",
"
amount
":
"
14027
",
"
delta
":
"
453
"
}
19
]
20
},
21
"
as_of
":
1369981898
22 }
其中的"2013-05-31 14:31"是变化的key,如何获取其中的"name","query","amount","delta"等信息呢?
通过Linq可以很简单地做到:
var jObj =
JObject.Parse(jsonString);
var tends =
from c
in
jObj.First.First.First.First.Children()
selectJsonConvert.DeserializeObject
(c.ToString());
public
class
Trend{
public
string Name {
get;
set
; }
public
string Query {
get;
set
; }
public
string Amount {
get;
set
; }
public
string Delta {
get;
set
; }}