Deserialize JSON into C# dynamic object?

2018-12-30 23:48发布

Is there a way to deserialize JSON content into a C# 4 dynamic type? It would be nice to skip creating a bunch of classes in order to use the DataContractJsonSerializer.

24条回答
浪荡孟婆
2楼-- · 2018-12-31 00:02

Another way using Newtonsoft.Json:

dynamic stuff = Newtonsoft.Json.JsonConvert.DeserializeObject("{ color: 'red', value: 5 }");
string color = stuff.color;
int value = stuff.value;
查看更多
一个人的天荒地老
3楼-- · 2018-12-31 00:02

There is a lightweight json library for C# called SimpleJson which can be found at http://simplejson.codeplex.com https://github.com/facebook-csharp-sdk/simple-json

It supports .net 3.5+, silverlight and windows phone 7.

Supports dynamic for .net 4.0

Can also be installed as a nuget package

Install-Package SimpleJson
查看更多
宁负流年不负卿
4楼-- · 2018-12-31 00:03

Its probably a little late to help you but the object you want DynamicJSONObject is included in the System.Web.Helpers.dll from the ASP.NET Web Pages package, which is part of WebMatrix.

查看更多
残风、尘缘若梦
5楼-- · 2018-12-31 00:04

Another option is to "Paste JSON as classes" so it can be deserialised quick and easy.

  1. Simply copy your entire JSON
  2. In VS: Click Edit > Paste Special > Paste JSON as classes

Here is a better explanation n piccas... https://blogs.msdn.microsoft.com/webdev/2012/12/18/paste-json-as-classes-in-asp-net-and-web-tools-2012-2-rc/

查看更多
深知你不懂我心
6楼-- · 2018-12-31 00:06

Simple "string json data" to object without any third party dll

WebClient client = new WebClient();
string getString = client.DownloadString("https://graph.facebook.com/zuck");


JavaScriptSerializer serializer = new JavaScriptSerializer(); 
dynamic item = serializer.Deserialize<object>(getString);
string name = item["name"];

//note: JavaScriptSerializer in this namespaces
//System.Web.Script.Serialization.JavaScriptSerializer 

Note : You can also using your custom object.

Personel item = serializer.Deserialize<Personel>(getString);
查看更多
倾城一夜雪
7楼-- · 2018-12-31 00:07

Simplest way is

Just include this dll

use the code like this

dynamic json = new JDynamic("{a:'abc'}");
//json.a is a string "abc"

dynamic json = new JDynamic("{a:3.1416}");
//json.a is 3.1416m

dynamic json = new JDynamic("{a:1}");
//json.a is

dynamic json = new JDynamic("[1,2,3]");
/json.Length/json.Count is 3
//And you can use json[0]/ json[2] to get the elements

dynamic json = new JDynamic("{a:[1,2,3]}");
//json.a.Length /json.a.Count is 3.
//And you can use  json.a[0]/ json.a[2] to get the elements

dynamic json = new JDynamic("[{b:1},{c:1}]");
//json.Length/json.Count is 2.
//And you can use the  json[0].b/json[1].c to get the num.
查看更多
登录 后发表回答