[翻译]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(, , ));
4
5 array.Add(text);
6 array.Add(date);
7
8 string json = array.ToString();
//生成的Json字符窜如下:
// [
// "Manual text",
// "\/Date(958996800000+1200)\/"
// ]
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."),
new JProperty("item",
new JArray(
from p in posts
orderby p.Title
select new JObject(
new JProperty("title", p.Title),
new JProperty("description", p.Description),
new JProperty("link", p.Link),
new JProperty("category",
new JArray(
from c in p.Categories
select new JValue(c)))))))));
Console.WriteLine(rss.ToString());
//生成的Json字符窜如下:
//{
// "channel": {
// "title": "James Newton-King",
// "link": "http://james.newtonking.com",
// "description": "James Newton-King's blog.",
// "item": [
// {
// "title": "Json.NET 1.3 + New license + Now on CodePlex",
// "description": "Annoucing the release of Json.NET 1.3, the MIT license and the source being available on CodePlex",
// "link": "http://james.newtonking.com/projects/json-net.aspx",
// "category": [
// "Json.NET",
// "CodePlex"
// ]
// },
// {
// "title": "LINQ to JSON beta",
// "description": "Annoucing LINQ to JSON",
// "link": "http://james.newtonking.com/projects/json-net.aspx",
// "category": [
// "Json.NET",
// "LINQ"
// ]
// }
// ]
// }
//}
分析一下: 如果按照普通方法把一个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
orderby p.Title
select new
{
title = p.Title,
description = p.Description,
link = p.Link,
category = p.Categories
}
}
});
最后可以通过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
//LINQ to JSON beta
//Json.NET 1.3 + New license + Now on CodePlex
var categories =
from c in rss["channel"]["item"].Children()["category"].Values<string>()
group c by c into g
orderby g.Count() descending
select new { Category = g.Key, Count = g.Count() };
foreach (var c in categories)
{
Console.WriteLine(c.Category + " - Count: " + c.Count);
}
//Json.NET - Count: 2
//LINQ - Count: 1
//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
{
public int Code { get; set; }
public string ErrorMessage { get; set; }
}
手动之间的序列化和反序列化一个.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
JObject json = JObject.Parse(jsonText);
Shortie shortie = new Shortie
{
Original = (string)json["short"]["original"],
Short = (string)json["short"]["short"],
Error = new ShortieException
{
Code = (int)json["short"]["error"]["code"],
ErrorMessage = (string)json["short"]["error"]["msg"]
}
};
Console.WriteLine(shortie.Original);
// http://www.foo.com/
Console.WriteLine(shortie.Error.ErrorMessage);
// No action taken
个人翻译不是很好,最近主要是用的比较频繁. 今天总结一些基本用法.如想看原版的Linq To Json 编译 请参考官方地址下API,代码如果看不懂可以查看Newtonsoft.Json.Linq命名空间下定义类和集成静待方法或直接联系我.
/******************************************************************************************
*【Author】:chenkai
*【Date】:2013年06月22日
*【Notice】:
*1、本文为原创技术文章,首发博客园个人站点(http://www.cnblogs.com/chenkai/archive/2010/01/02/1637704.html),转载和引用请注明作者及出处。
*2、本文必须全文转载和引用,任何组织和个人未授权不能修改任何内容,并且未授权不可用于商业。
*3、本声明为文章一部分,转载和引用必须包括在原文中。
******************************************************************************************/
[翻译]Json.NET API-Linq to Json Basic Operator(基本操作)【转】的更多相关文章
- 在JS和.NET中使用JSON (以及使用Linq to JSON定制JSON数据)
转载原地址: http://www.cnblogs.com/mcgrady/archive/2013/06/08/3127781.html 阅读目录 JSON的两种结构 认识JSON字符串 在JS中如 ...
- Json.Net 中Linq to JSON的操作
Linq to JSON是用来操作JSON对象的.可以用于快速查询,修改和创建JSON对象.当JSON对象内容比较复杂,而我们仅仅需要其中的一小部分数据时,可以考虑使用Linq to JSON来读取和 ...
- api接口返回动态的json格式?我太难了,尝试一下 linq to json
一:背景 1. 讲故事 前段时间和一家公司联调api接口的时候,发现一个奇葩的问题,它的api返回的json会动态改变,简化如下: {"Code":101,"Items& ...
- 【ASP.NET Web API教程】6.2 ASP.NET Web API中的JSON和XML序列化
谨以此文感谢关注此系列文章的园友!前段时间本以为此系列文章已没多少人关注,而不打算继续下去了.因为文章贴出来之后,看的人似乎不多,也很少有人对这些文章发表评论,而且几乎无人给予“推荐”.但前几天有人询 ...
- Asp.Net Web API 2第十三课——ASP.NET Web API中的JSON和XML序列化
前言 阅读本文之前,您也可以到Asp.Net Web API 2 系列导航进行查看 http://www.cnblogs.com/aehyok/p/3446289.html 本文描述ASP.NET W ...
- ASP.NET Web API中的JSON和XML序列化
ASP.NET Web API中的JSON和XML序列化 前言 阅读本文之前,您也可以到Asp.Net Web API 2 系列导航进行查看 http://www.cnblogs.com/aehyok ...
- Python第十四天 序列化 pickle模块 cPickle模块 JSON模块 API的两种格式
Python第十四天 序列化 pickle模块 cPickle模块 JSON模块 API的两种格式 目录 Pycharm使用技巧(转载) Python第一天 安装 shell 文件 Py ...
- C# web Api ajax发送json对象到action中
直接上代码: 1.Product实体
- c#代码 天气接口 一分钟搞懂你的博客为什么没人看 看完python这段爬虫代码,java流泪了c#沉默了 图片二进制转换与存入数据库相关 C#7.0--引用返回值和引用局部变量 JS直接调用C#后台方法(ajax调用) Linq To Json SqlServer 递归查询
天气预报的程序.程序并不难. 看到这个需求第一个想法就是只要找到合适天气预报接口一切都是小意思,说干就干,立马跟学生沟通价格. 不过谈报价的过程中,差点没让我一口老血喷键盘上,话说我们程序猿的人 ...
随机推荐
- 使用DBCC SHOW_STATISTICS展示索引的统计信息
在开始之前搭建演示环境: USE master GO SET NOCOUNT ON --创建表结构 IF OBJECT_ID(N'ClassA', N'U') IS NOT NULL DROP TAB ...
- sqlserver 删掉日志文件ldf以后 救命语句
sqlserver 删掉日志文件ldf以后 救命步骤: 先新建一个新数据库, 删掉新建的 .mdb 用想要还原的mdb覆盖 执行下面的语句 ALTER DATABASE 'DB_Core' SET ...
- oracle 10g
一.安装系统 首先安装Linux系统,根据Oracle官方文档的建议,在机器内存小于1G的情况下,swap分区大小应该设置为内存的2倍大,若内存大于2G则swap分区设置为与内存大小一样. 为防止Or ...
- codeforces 630KIndivisibility(容斥原理)
K. Indivisibility time limit per test 0.5 seconds memory limit per test 64 megabytes input standard ...
- 算法之旅,直奔<algorithm>之十七 find_first_of
find_first_of(vs2010) 引言 这是我学习总结 <algorithm>的第十七篇,find_first_of是匹配的一个函数.<algorithm>是c++的 ...
- Javascript继承实现
S1:js中一切皆对象,想想如果要实现对父对象属性和方法的继承,最初我们会怎样子来实现呢,考虑到原型的概念,最初我是这样来实现继承的 function Parent(){ this.name='123 ...
- android 多线程数据库读写分析与优化
最新需要给软件做数据库读写方面的优化,之前无论读写,都是用一个 SQLiteOpenHelper.getWriteableDataBase() 来操作数据库,现在需要多线程并发读写,项目用的是2.2的 ...
- webpack echarts配置实例
简单介绍 本例介绍怎样在webpack中构建依赖echats的项目,echarts有好几种方式引入项目: 标签单文件引入:自1.3.5開始,ECharts提供标签式引入.假设项目本身并非基于模块化开发 ...
- C#操作Word (1)Word对象模型
Word对象模型 (.Net Perspective) 本文主要针对在Visual Studio中使用C# 开发关于Word的应用程序 来源:Understandingthe Word Object ...
- 不用submit 同样实现button 点击enter键进行提交
$(function(){ document.onkeydown = function (e) { var theEvent = window.event || e; var code = theEv ...