原文 https://weblog.west-wind.com/posts/2012/Aug/30/Using-JSONNET-for-dynamic-JSON-parsing

With the release of ASP.NET Web API as part of .NET 4.5 and MVC 4.0, JSON.NET has effectively pushed out the .NET native serializers to become the default serializer for Web API. JSON.NET is vastly more flexible than the built in DataContractJsonSerializer or the older JavaScript serializer. The DataContractSerializer in particular has been very problematic in the past because it can't deal with untyped objects for serialization - like values of type object, or anonymous types which are quite common these days. The JavaScript Serializer that came before it actually does support non-typed objects for serialization but it can't do anything with untyped data coming in from JavaScript and it's overall model of extensibility was pretty limited (JavaScript Serializer is what MVC uses for JSON responses).

JSON.NET provides a robust JSON serializer that has both high level and low level components, supports binary JSON, JSON contracts, Xml to JSON conversion, LINQ to JSON and many, many more features than either of the built in serializers. ASP.NET Web API now uses JSON.NET as its default serializer and is now pulled in as a NuGet dependency into Web API projects, which is great.

Dynamic JSON Parsing

One of the features that I think is getting ever more important is the ability to serialize and deserialize arbitrary JSON content dynamically - that is without mapping the JSON captured directly into a .NET type as DataContractSerializer or the JavaScript Serializers do. Sometimes it isn't possible to map types due to the differences in languages (think collections, dictionaries etc), and other times you simply don't have the structures in place or don't want to create them to actually import the data.

If this topic sounds familiar - you're right! I wrote about dynamic JSON parsing a few months back before JSON.NET was added to Web API and when Web API and the System.Net HttpClient libraries included the System.Json classes like JsonObject and JsonArray. With the inclusion of JSON.NET in Web API these classes are now obsolete and didn't ship with Web API or the client libraries. I re-linked my original post to this one. In this post I'll discus JToken, JObject and JArray which are the dynamic JSON objects that make it very easy to create and retrieve JSON content on the fly without underlying types.

Why Dynamic JSON?

So, why Dynamic JSON parsing rather than strongly typed parsing? Since applications are interacting more and more with third party services it becomes ever more important to have easy access to those services with easy JSON parsing. Sometimes it just makes lot of sense to pull just a small amount of data out of large JSON document received from a service, because the third party service isn't directly related to your application's logic most of the time - and it makes little sense to map the entire service structure in your application.

For example, recently I worked with the Google Maps Places API to return information about businesses close to me (or rather the app's) location. The Google API returns a ton of information that my application had no interest in - all I needed was few values out of the data. Dynamic JSON parsing makes it possible to map this data, without having to map the entire API to a C# data structure. Instead I could pull out the three or four values I needed from the API and directly store it on my business entities that needed to receive the data - no need to map the entire Maps API structure.

Getting JSON.NET

The easiest way to use JSON.NET is to grab it via NuGet and add it as a reference to your project. You can add it to your project with:

PM> Install-Package Newtonsoft.Json

From the Package Manager Console or by using Manage NuGet Packages in your project References. As mentioned if you're using ASP.NET Web API or MVC 4 JSON.NET will be automatically added to your project.

Alternately you can also go to the CodePlex site and download the latest version including source code:

http://json.codeplex.com/

Creating JSON on the fly with JObject and JArray

Let's start with creating some JSON on the fly. It's super easy to create a dynamic object structure with any of the JToken derived JSON.NET objects. The most common JToken derived classes you are likely to use are JObject and JArray.

JToken implements IDynamicMetaProvider and so uses the dynamic  keyword extensively to make it intuitive to create object structures and turn them into JSON via dynamic object syntax. Here's an example of creating a music album structure with child songs using JObject for the base object and songs and JArray for the actual collection of songs:

[TestMethod]
public void JObjectOutputTest()
{
// strong typed instance
var jsonObject = new JObject(); // you can explicitly add values here using class interface
jsonObject.Add("Entered", DateTime.Now); // or cast to dynamic to dynamically add/read properties dynamic album = jsonObject; album.AlbumName = "Dirty Deeds Done Dirt Cheap";
album.Artist = "AC/DC";
album.YearReleased = 1976; album.Songs = new JArray() as dynamic; dynamic song = new JObject();
song.SongName = "Dirty Deeds Done Dirt Cheap";
song.SongLength = "4:11";
album.Songs.Add(song); song = new JObject();
song.SongName = "Love at First Feel";
song.SongLength = "3:10";
album.Songs.Add(song); Console.WriteLine(album.ToString());
}

This produces a complete JSON structure:

{
"Entered": "2012-08-18T13:26:37.7137482-10:00",
"AlbumName": "Dirty Deeds Done Dirt Cheap",
"Artist": "AC/DC",
"YearReleased": 1976,
"Songs": [
{
"SongName": "Dirty Deeds Done Dirt Cheap",
"SongLength": "4:11"
},
{
"SongName": "Love at First Feel",
"SongLength": "3:10"
}
]
}

Notice that JSON.NET does a nice job formatting the JSON, so it's easy to read and paste into blog posts

Using-JSONNET-for-dynamic-JSON-parsing的更多相关文章

  1. Google提议使用Jsonnet来增强JSON

    Google开源了一门配置语言Jsonnet来取代JSON,它完全向后兼容并加入了一些新特性:注释.引用.算术运算.条件操作符,数组和对象内含,引入,函数,局部变量,继承等.Jsonnet程序被翻译为 ...

  2. C# dynamic json

    对应普通对象,写个扩展方法,ToJson蛮方便. 但是 dynamic 类型就不行了,因为是运行时解析,只能转换为强类型 IDictionary<string, object> 才可以. ...

  3. 关于 C# HttpClient的 请求

    Efficiently Streaming Large HTTP Responses With HttpClient Downloading large files with HttpClient a ...

  4. 使用 dynamic 标记解析JSON字符串 JDynamic :支持Json反序列化为Dynamic对象

    使用 dynamic 标记解析JSON字符串  http://www.cnblogs.com/taotaodetuer/p/4171327.html 1 string jsonStr = " ...

  5. 使用dynamic获取类型可变的json对象

    标题可能有点含糊不清 我这个例子的来源是,对方会返回给我json,不过成功的json与失败的json是不同的对象 我想用一个方法获取到这个对象的所有属性并打印到log中 因为是动态变化的,所以第一个想 ...

  6. Json.net实现方便的Json转C#(dynamic动态类型)对象

    以前需要将一段json字符串转换为C#对象时,一般都是定义一个与之对应的实体类来接收.这样做有一个很大的缺点,就是当字符串特别长,属性特别多,又有嵌套时,手敲这个实体类就非常痛苦. 比如之前做的一个接 ...

  7. JDynamic :支持Json反序列化为Dynamic对象

    JDynamic :支持Json反序列化为Dynamic对象   2010年 .NET 4.0 发布前后,从3.5向4.0迁移,那时也有一些异构系统的需求,主要是和PHP打交道,通信使用的HTTP 格 ...

  8. 『动态』动态JSON万能转换函数 + .Net40 dynamic动态数据绑定

    不废话,调用代码: static void Main(string[] args) { string json = File.ReadAllText("2.txt", Encodi ...

  9. c# json转换成dynamic对象,然后在dynamic对象中动态获取指定字符串列表中的值

    using Newtonsoft.Json;using System;using System.Collections.Generic;using System.Linq;using System.T ...

随机推荐

  1. Codeforces Round #420 (Div. 2) - C

    题目链接:http://codeforces.com/contest/821/problem/C 题意:起初有一个栈,给定2*n个命令,其中n个命令是往栈加入元素,另外n个命令是从栈中取出元素.你可以 ...

  2. [BJOI2006]狼抓兔子(网络流)

    题目描述 现在小朋友们最喜欢的"喜羊羊与灰太狼",话说灰太狼抓羊不到,但抓兔子还是比较在行的,而且现在的兔子还比较笨,它们只有两个窝,现在你做为狼王,面对下面这样一个网格的地形: ...

  3. [POJ1821]Fence(单调队列优化dp)

    [poj1821]Fence 有 N 块木板从左至右排成一行,有 M 个工匠对这些木板进行粉刷,每块木板至多被粉刷一次.第 i 个工匠要么不粉刷,要么粉刷包含木板 Si 的,长度不超过Li 的连续一段 ...

  4. java 大数运算,高精度模板

    转自:https://blog.csdn.net/stffer/article/details/46382949 有修改 关于BigInteger类更详细的用法请移步官方文档 package prac ...

  5. 用setInterval方法实现弹框闪烁

    每次看到某电商平台的拼团提示会觉得很有趣也很方便,正好自己在学习小程序,那就想个法子实现一下这种效果咯~思虑了一下还是觉得用setIntercal方法比较简便(数据方面就先不考虑了,我这里只做一下表现 ...

  6. toj 4061 矩阵攻击(最大独立集)

    题目: 给定一个01 矩阵,其中你可以在0的位置放置攻击装置.每一个攻击装置 (x,y) 都可以按照“日”字攻击其周围八个位置(x−1,y−2),(x−2,y−1),(x+1,y−2),(x+2,y− ...

  7. java list集合元素根据某些字段排序

    一.jdk1.6的环境下 新建ComparatorSort类,并实现Comparator接口,重写compare方法 降序排序:o1的元素>o2的元素,并返回-1:o1的元素小于o2的元素,并返 ...

  8. boost variant

    Boost Variant resembles union. You can store values of different types in a boost::variant. 1. #incl ...

  9. php strtoupper()函数 语法

    php strtoupper()函数 语法 作用:把所有字符转换为大写 语法:strtoupper(string) 参数: 参数 描述 string 必须,规定要转换的字符串 说明:strtouppe ...

  10. 09-排序3 Insertion or Heap Sort(25 分)

    According to Wikipedia: Insertion sort iterates, consuming one input element each repetition, and gr ...