灌木大叔

每一个不曾起舞的日子都是对以往生命的辜负!!

  :: 首页 :: 博问 :: 闪存 :: :: 联系 :: 订阅 订阅 :: 管理 ::
  89 随笔 :: 114 文章 :: 4 评论 :: 22万 阅读

Newtonsoft.Json使用
序列化和反序列化JSON
使用JSON路径查询JSON
使用JSON路径和转义属性查询JSON
使用复杂JSON路径查询JSON
使用JSON路径和LINQ查询JSON
JSON路径和正则
JSON路径等于比较操作
ToDictionary
序列化和反序列化JSON
在JSON文本和.NET对象之间转换的最快方法是使用Json序列化器…JsonSeriizer通过将.NET对象属性名称映射到JSON属性名称,并为您复制值,将.NET对象转换为其等效的JSON并再次返回。

JsonConvert
Json序列化器
JsonConvert
对于要转换到JSON字符串和从JSON字符串转换的简单场景,序列化对象()和反序列化对象()方法在JsonSeriizer上提供了一个易于使用的包装器.
用JsonConvert序列化和反序列化JSON

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Product product = new Product();
 
product.Name = "Apple";
product.ExpiryDate = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
 
string output = JsonConvert.SerializeObject(product);
//{
//  "Name": "Apple",
//  "ExpiryDate": "2008-12-28T00:00:00",
//  "Price": 3.99,
//  "Sizes": [
//    "Small",
//    "Medium",
//    "Large"
//  ]
//}
 
Product deserializedProduct = JsonConvert.DeserializeObject<Product>(output);

 

SerializeObject和DeserializeObject都具有一个JsonSerializerSettings对象。JsonSerializerSettings允许您在使用简单序列化方法的同时使用下面列出的许多JsonSeriizerSettings设置。

Json序列化器
有关如何序列化对象的更多控制,请使用Json序列化器可以直接使用。JsonSeriizer可以通过以下方式直接将JSON文本读写到流中JsonTextReader和JsonTextWriter…也可以使用其他类型的JsonWriter,例如JTokenReader/JTokenWriter,将对象从LINQ转换为JSON对象,或BsonReader/BsonWriter,转换为BSON或BSON。

用JsonSeriizer将JSON序列化为流

1
2
3
4
5
6
7
8
9
10
11
12
13
Product product = new Product();
product.ExpiryDate = new DateTime(2008, 12, 28);
 
JsonSerializer serializer = new JsonSerializer();
serializer.Converters.Add(new JavaScriptDateTimeConverter());
serializer.NullValueHandling = NullValueHandling.Ignore;
 
using (StreamWriter sw = new StreamWriter(@"c:\json.txt"))
using (JsonWriter writer = new JsonTextWriter(sw))
{
serializer.Serialize(writer, product);
// {"ExpiryDate":new Date(1230375600000),"Price":0}
}

 

使用JSON路径查询JSON

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
JObject o = JObject.Parse(@"{
'Stores': [
'Lambton Quay',
'Willis Street'
],
'Manufacturers': [
{
'Name': 'Acme Co',
'Products': [
{
'Name': 'Anvil',
'Price': 50
}
]
},
{
'Name': 'Contoso',
'Products': [
{
'Name': 'Elbow Grease',
'Price': 99.95
},
{
'Name': 'Headlight Fluid',
'Price': 4
}
]
}
]
}");
 
string name = (string)o.SelectToken("Manufacturers[0].Name");
 
Console.WriteLine(name);
// Acme Co
 
decimal productPrice = (decimal)o.SelectToken("Manufacturers[0].Products[0].Price");
 
Console.WriteLine(productPrice);
// 50
 
string productName = (string)o.SelectToken("Manufacturers[1].Products[0].Name");
 
Console.WriteLine(productName);
// Elbow Grease

 

使用JSON路径和转义属性查询JSON

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
JObject o = JObject.Parse(@"{
'Space Invaders': 'Taito',
'Doom ]|[': 'id',
""Yar's Revenge"": 'Atari',
'Government ""Intelligence""': 'Make-Believe'
}");
 
string spaceInvaders = (string)o.SelectToken("['Space Invaders']");
// Taito
 
string doom3 = (string)o.SelectToken("['Doom ]|[']");
// id
 
string yarsRevenge = (string)o.SelectToken("['Yar\\'s Revenge']");
// Atari
 
string governmentIntelligence = (string)o.SelectToken("['Government \"Intelligence\"']");
// Make-Believe

 

使用复杂JSON路径查询JSON

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
JObject o = JObject.Parse(@"{
'Stores': [
'Lambton Quay',
'Willis Street'
],
'Manufacturers': [
{
'Name': 'Acme Co',
'Products': [
{
'Name': 'Anvil',
'Price': 50
}
]
},
{
'Name': 'Contoso',
'Products': [
{
'Name': 'Elbow Grease',
'Price': 99.95
},
{
'Name': 'Headlight Fluid',
'Price': 4
}
]
}
]
}");
 
// manufacturer with the name 'Acme Co'
JToken acme = o.SelectToken("$.Manufacturers[?(@.Name == 'Acme Co')]");
 
Console.WriteLine(acme);
// { "Name": "Acme Co", Products: [{ "Name": "Anvil", "Price": 50 }] }
 
// name of all products priced 50 and above
IEnumerable<JToken> pricyProducts = o.SelectTokens("$..Products[?(@.Price >= 50)].Name");
 
foreach (JToken item in pricyProducts)
{
Console.WriteLine(item);
}
// Anvil

 

使用JSON路径和LINQ查询JSON

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
JObject o = JObject.Parse(@"{
'Stores': [
'Lambton Quay',
'Willis Street'
],
'Manufacturers': [
{
'Name': 'Acme Co',
'Products': [
{
'Name': 'Anvil',
'Price': 50
}
]
},
{
'Name': 'Contoso',
'Products': [
{
'Name': 'Elbow Grease',
'Price': 99.95
},
{
'Name': 'Headlight Fluid',
'Price': 4
}
]
}
]
}");
 
string[] storeNames = o.SelectToken("Stores").Select(s => (string)s).ToArray();
 
Console.WriteLine(string.Join(", ", storeNames));
// Lambton Quay, Willis Street
 
string[] firstProductNames = o["Manufacturers"].Select(m => (string)m.SelectToken("Products[1].Name"))
.Where(n => n != null).ToArray();
 
Console.WriteLine(string.Join(", ", firstProductNames));
// Headlight Fluid
 
decimal totalPrice = o["Manufacturers"].Sum(m => (decimal)m.SelectToken("Products[0].Price"));
 
Console.WriteLine(totalPrice);
// 149.95

 

JSON路径和正则

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
JArray packages = JArray.Parse(@"[
{
'PackageId': 'Newtonsoft.Json',
'Version': '11.0.1',
'ReleaseDate': '2018-02-17T00:00:00'
},
{
'PackageId': 'NUnit',
'Version': '3.9.0',
'ReleaseDate': '2017-11-10T00:00:00'
}
]");
 
// Find Newtonsoft packages
List<JToken> newtonsoftPackages = packages.SelectTokens(@"$.[?(@.PackageId =~ /^Newtonsoft\.(.*)$/)]").ToList();
 
foreach (JToken item in newtonsoftPackages)
{
Console.WriteLine((string) item["PackageId"]);
}
// Newtonsoft.Json

 

JSON路径等于比较操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
JArray items = JArray.Parse(@"[
{
'Name': 'Valid JSON',
'Valid': true
},
{
'Name': 'Invalid JSON',
'Valid': 'true'
}
]");
 
// Use === operator. Compared types must be the same to be valid
List<JToken> strictResults = items.SelectTokens(@"$.[?(@.Valid === true)]").ToList();
 
foreach (JToken item in strictResults)
{
Console.WriteLine((string)item["Name"]);
}
// Valid JSON

 

ToDictionary

1
Dictionary<string, string> dictionary = rates.ToDictionary(pair => pair.Key, pair => (string)pair.Value);

 

————————————————
版权声明:本文为CSDN博主「XBMY」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/cxb2011/article/details/103776939

posted on   灌木大叔  阅读(1577)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示