[翻译]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对象. 简单方法虽然能够创建,但是对编码而言较多略显累赘.简单创建代码如下:

1 JArray array = new JArray();
 2 JValue text = new JValue("Manual text");
 3 JValue date = new JValue(new DateTime(2000, 5, 23));
 4  
 5 array.Add(text);
 6 array.Add(date);
 7  
 8 string json = array.ToString();
10 //生成的Json字符窜如下:
11 // [
12 //   "Manual text",
13 //   "\/Date(958996800000+1200)\/"
14 // ] 

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

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

1 List<Post> posts = GetPosts();
 2  
 3 JObject rss =
 4   new JObject(
 5     new JProperty("channel",
 6       new JObject(
 7         new JProperty("title", "James Newton-King"),
 8         new JProperty("link", "http://james.newtonking.com"),
 9         new JProperty("description", "James Newton-King's blog."),
10         new JProperty("item",
11           new JArray(
12             from p in posts
13             orderby p.Title
14             select new JObject(
15               new JProperty("title", p.Title),
16               new JProperty("description", p.Description),
17               new JProperty("link", p.Link),
18               new JProperty("category",
19                 new JArray(
20                   from c in p.Categories
21                   select new JValue(c)))))))));
22  
23 Console.WriteLine(rss.ToString());
24 //生成的Json字符窜如下:
25 //{
26 //  "channel": {
27 //    "title": "James Newton-King",
28 //    "link": "http://james.newtonking.com",
29 //    "description": "James Newton-King's blog.",
30 //    "item": [
31 //      {
32 //        "title": "Json.NET 1.3 + New license + Now on CodePlex",
33 //        "description": "Annoucing the release of Json.NET 1.3, the MIT license and the source being available on CodePlex",
34 //        "link": "http://james.newtonking.com/projects/json-net.aspx",
35 //        "category": [
36 //          "Json.NET",
37 //          "CodePlex"
38 //        ]
39 //      },
40 //      {
41 //        "title": "LINQ to JSON beta",
42 //        "description": "Annoucing LINQ to JSON",
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.(自定义对象):

1 JObject o = JObject.FromObject(new
 2 {
 3   channel = new
 4   {
 5     title = "James Newton-King",
 6     link = "http://james.newtonking.com",
 7     description = "James Newton-King's blog.",
 8     item =
 9         from p in posts
10         orderby p.Title
11         select new
12         {
13           title = p.Title,
14           description = p.Description,
15           link = p.Link,
16           category = p.Categories
17         }
18   }
19 });

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

1 string json = @"{
 2   CPU: 'Intel',
 3   Drives: [
 4     'DVD read/writer',
 5     ""500 gigabyte hard drive""
 6   ]
 7 }";
 8  
 9 JObject o = JObject.Parse(json); 

B:查询Json Object

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

1 var postTitles =
 2   from p in rss["channel"]["item"].Children()
 3   select (string)p["title"];
 4  
 5 foreach (var item in postTitles)
 6 {
 7   Console.WriteLine(item);
 8 }
 9  
10 //LINQ to JSON beta
11 //Json.NET 1.3 + New license + Now on CodePlex
12  
13 var categories =
14   from c in rss["channel"]["item"].Children()["category"].Values<string>()
15   group c by c into g
16   orderby g.Count() descending
17   select new { Category = g.Key, Count = g.Count() };
18  
19 foreach (var c in categories)
20 {
21   Console.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对象 .

1 public class Shortie
 2 {
 3   public string Original { get; set; }
 4   public string Shortened { get; set; }
 5   public string Short { get; set; }
 6   public ShortieException Error { get; set; }
 7 }
 8  
 9 public class ShortieException
10 {
11   public int Code { get; set; }
12   public string ErrorMessage { get; set; }
13 }

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

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

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



本文转自chenkaiunion 51CTO博客,原文链接:http://blog.51cto.com/chenkai/765198

相关文章
|
JSON API 数据格式
淘宝/天猫图片搜索API接口,json返回数据。
淘宝/天猫平台虽未开放直接的图片搜索API,但可通过阿里妈妈淘宝联盟或天猫开放平台接口实现类似功能。本文提供基于淘宝联盟的图片关联商品搜索Curl示例及JSON响应说明,适用于已获权限的开发者。如需更高精度搜索,可选用阿里云视觉智能API。
|
JSON API 数据安全/隐私保护
深度分析淘宝卖家订单详情API接口,用json返回数据
淘宝卖家订单详情API(taobao.trade.fullinfo.get)是淘宝开放平台提供的重要接口,用于获取单个订单的完整信息,包括订单状态、买家信息、商品明细、支付与物流信息等,支撑订单管理、ERP对接及售后处理。需通过appkey、appsecret和session认证,并遵守调用频率与数据权限限制。本文详解其使用方法并附Python调用示例。
|
机器学习/深度学习 JSON 监控
淘宝拍立淘按图搜索与商品详情API的JSON数据返回详解
通过调用taobao.item.get接口,获取商品标题、价格、销量、SKU、图片、属性、促销信息等全量数据。
|
JSON API 数据格式
淘宝拍立淘按图搜索API系列,json数据返回
淘宝拍立淘按图搜索API系列通过图像识别技术实现商品搜索功能,调用后返回的JSON数据包含商品标题、图片链接、价格、销量、相似度评分等核心字段,支持分页和详细商品信息展示。以下是该API接口返回的JSON数据示例及详细解析:
|
JSON 算法 API
Python采集淘宝商品评论API接口及JSON数据返回全程指南
Python采集淘宝商品评论API接口及JSON数据返回全程指南
|
JSON 缓存 自然语言处理
多语言实时数据微店商品详情API:技术实现与JSON数据解析指南
通过以上技术实现与解析指南,开发者可高效构建支持多语言的实时商品详情系统,满足全球化电商场景需求。
|
JSON API 数据安全/隐私保护
Python采集淘宝拍立淘按图搜索API接口及JSON数据返回全流程指南
通过以上流程,可实现淘宝拍立淘按图搜索的完整调用链路,并获取结构化的JSON商品数据,支撑电商比价、智能推荐等业务场景。
|
JSON API 数据格式
干货满满!淘宝商品详情数据,淘宝API(json数据返回)
淘宝商品详情 API 接口(如 taobao.item.get)的 JSON 数据返回示例如下
|
JSON 算法 安全
淘宝商品详情API接口系列,json数据返回
淘宝开放平台提供了多种API接口用于获取商品详情信息,主要通过 淘宝开放平台(Taobao Open Platform, TOP) 的 taobao.tbk.item.info.get(淘宝客商品详情)或 taobao.item.get(标准商品API)等接口实现。以下是关键信息及JSON返回示例:
|
设计模式 JSON Unix
微店商品详情API接口,json数据返回
微店商品详情API接口的典型JSON返回数据结构说明,基于公开的微店开放平台API文档和常见电商API设计模式整理。实际使用时请以微店官方最新文档为准

热门文章

最新文章