微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

[翻译]Json.NET API-Linq to Json Basic Operator(基本操作)

在Json.NET开源的组件的api文档中看到其中有个Linq To Json基本操作.详细看了其中API 中Linq to sql命名空间下定义类方法.以及实现,觉得参与Linq 来操作Json从某种程度上提高生成Json字符窜的效率,特别对数据库中批量的数据. 但是也从侧面也增加程序员编码的难度(如果刚用不熟练情况下 主要是在编码中控制生成Json字符窜正确的格式),另外一个关键借助了Linq对Json数据操作和转换更加直接.Linq To sql 空间目的使用户利用Linq更加直接创建和查询Json对象. 翻译文档如下:

A:Creating Json-(利用Linq快速创建Json Object)

Newtonsoft.Json.Linq 空间下有多个方法可以创建一个Json对象. 简单方法虽然能够创建,但是对编码而言较多略显累赘.简单创建代码如下:

1JArrayarray=newJArray();
2JValuetext=newJValue("Manualtext");
3JValuedate=newJValue(newDateTime(2000,5,23));
4
5array.Add(text);
6array.Add(date);
7
8stringjson=array.ToString();
10//生成的Json字符窜如下:
11//[
12//"Manualtext",
13//"\/Date(958996800000+1200)\/"
14//]

JArray是Newtonsoft.Json.Linq空间扩展的类表示一个Json数组.而JValue代表JSON值(字符串,整数,日期等) .

简单利用Linq To sql创建一个Json Object:

1List<Post>posts=GetPosts();
2
3JObjectRSS=
4newJObject(
5newJProperty("channel",
6newJObject(
7newJProperty("title","JamesNewton-King"),
8newJProperty("link","http://james.newtonking.com"),
9newJProperty("description","JamesNewton-King'sblog."),
10newJProperty("item",
11newJArray(
12frompinposts
13orderbyp.Title
14selectnewJObject(
15newJProperty("title",p.Title),
16newJProperty("description",p.Description),
17newJProperty("link",p.Link),
18newJProperty("category",
19newJArray(
20fromcinp.Categories
21selectnewJValue(c)))))))));
22
23Console.WriteLine(RSS.ToString());
24//生成的Json字符窜如下:
25//{
26//"channel":{
27//"title":"JamesNewton-King",
28//"link":"http://james.newtonking.com",
29//"description":"JamesNewton-King'sblog.",
30//"item":[
31//{
32//"title":"Json.NET1.3+Newlicense+NowonCodePlex",
33//"description":"AnnoucingthereleaSEOfJson.NET1.3,theMITlicenseandthesourcebeingavailableonCodePlex",
34//"link":"http://james.newtonking.com/projects/json-net.aspx",
35//"category":[
36//"Json.NET",
37//"CodePlex"
38//]
39//},
40//{
41//"title":"LINQtoJSONbeta",
42//"description":"AnnoucingLINQtoJSON",
43//"link":"http://james.newtonking.com/projects/json-net.aspx",
44//"category":[
45//"Json.NET",
46//"LINQ"
47//]
48//}
49//]
50//}
51//}

分析一下: 如果按照普通方法一个List集合生成Json对象字符窜.步骤如下: List首先从数据库中取出.然后利用JsonConvert实体类下的SerializeObject()方法实例化才能返回Json字符窜. 相对而言Linq 直接操作数据库数据 一步到位 所以在编程效率上实现提高.

你可以FromObject()方法一个非Json类型对象创建成Json Object.(自定义对象):

1JObjecto=JObject.FromObject(new
2{
3channel=new
4{
5title="JamesNewton-King",
6link="http://james.newtonking.com",
7description="JamesNewton-King'sblog.",
8item=
9frompinposts
10orderbyp.Title
11selectnew
12{
13title=p.Title,
14description=p.Description,
15link=p.Link,
16category=p.Categories
17}
18}
19});

最后可以通过Pares()方法一个String字符窜创建一个Json对象:(手写控制Json格式):

1stringjson=@"{
2cpu:'Intel',
3Drives:[
4'DVDread/writer',
5""500gigabyteharddrive""
6]
7}";
8
9JObjecto=JObject.Parse(json);

B:查询Json Object

查询一个Json Object属性时最有用方法分别为:Children()方法和Property Index(属性索引),Children()方法将返回Json Object所有的Json子实体. 如果它是一个JObject将返回一个属性集合.如果是JArray返回一个数组值的集合. 但是Property Index用户获得特定的Children子实体.无论是JSON数组索引或JSON对象的属性名的位置.

1varpostTitles=
2frompinRSS["channel"]["item"].Children()
3select(string)p["title"];
4
5foreach(variteminpostTitles)
6{
7Console.WriteLine(item);
8}
9
10//LINQtoJSONbeta
11//Json.NET1.3+Newlicense+NowonCodePlex
12
13varcategories=
14fromcinRSS["channel"]["item"].Children()["category"].Values<string>()
15groupcbycintog
16orderbyg.Count()descending
17selectnew{Category=g.Key,Count=g.Count()};
18
19foreach(varcincategories)
20{
21Console.WriteLine(c.Category+"-Count:"+c.Count);
22}
24//Json.NET-Count:2
25//LINQ-Count:1
26//CodePlex-Count:1

Linq to Json常常用于手动把一个Json Object转换成.NET对象 .

1publicclassShortie
2{
3publicstringOriginal{get;set;}
4publicstringShortened{get;set;}
5publicstringShort{get;set;}
6publicShortieExceptionError{get;set;}
7}
8
9publicclassShortieException
10{
11publicintCode{get;set;}
12publicstringErrorMessage{get;set;}
13}

手动之间的序列化和反序列化一个.NET对象是最常用情况是JSON Object和需要的。NET对象不匹配情况下.

1stringjsonText=@"{
2""short"":{
3""original"":""http://www.foo.com/"",
4""short"":""krehqk"",
5""error"":{
6""code"":0,
7""msg"":""Noactiontaken""}
8}";
9
10JObjectjson=JObject.Parse(jsonText);
11
12Shortieshortie=newShortie
13{
14Original=(string)json["short"]["original"],
15Short=(string)json["short"]["short"],
16Error=newShortieException
17{
18Code=(int)json["short"]["error"]["code"],
19ErrorMessage=(string)json["short"]["error"]["msg"]
20}
21};
22
23Console.WriteLine(shortie.Original);
24//http://www.foo.com/
25
26Console.WriteLine(shortie.Error.ErrorMessage);
27//Noactiontaken

个人翻译不是很好,最近主要是用的比较频繁. 今天总结一些基本用法.如想看原版的Linq To Json 编译 请参考官方地址下API,代码如果看不懂可以查看Newtonsoft.Json.Linq命名空间下定义类和集成静待方法或直接联系我.

原文地址:https://www.jb51.cc/json/290827.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐