我玩半条命12时自动存档会出现“Node Graph out o...

.net - Deserialize JSON into C# dynamic object? - Stack Overflow
to customize your list.
Join the Stack Overflow Community
Stack Overflow is a community of 6.4 million programmers, just like you, helping each other.
J it only takes a minute:
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.
131k76404499
4,45861415
If you are happy to have a dependency upon the System.Web.Helpers assembly, then you can use the
dynamic data = Json.Decode(json);
It is included with the MVC framework as an additional download to the .NET 4 framework. Be sure to give Vlad an upvote if that's helpful! However if you cannot assume the client environment includes this DLL, then read on.
An alternative deserialisation approach is suggested .
I modified the code slightly to fix a bug and suit my coding style.
All you need is this code and a reference to System.Web.Extensions from your project:
using System.C
using System.Collections.G
using System.Collections.ObjectM
using System.D
using System.L
using System.T
using System.Web.Script.S
public sealed class DynamicJsonConverter : JavaScriptConverter
public override object Deserialize(IDictionary&string, object& dictionary, Type type, JavaScriptSerializer serializer)
if (dictionary == null)
throw new ArgumentNullException("dictionary");
return type == typeof(object) ? new DynamicJsonObject(dictionary) :
public override IDictionary&string, object& Serialize(object obj, JavaScriptSerializer serializer)
throw new NotImplementedException();
public override IEnumerable&Type& SupportedTypes
get { return new ReadOnlyCollection&Type&(new List&Type&(new[] { typeof(object) })); }
#region Nested type: DynamicJsonObject
private sealed class DynamicJsonObject : DynamicObject
private readonly IDictionary&string, object& _
public DynamicJsonObject(IDictionary&string, object& dictionary)
if (dictionary == null)
throw new ArgumentNullException("dictionary");
_dictionary =
public override string ToString()
var sb = new StringBuilder("{");
ToString(sb);
return sb.ToString();
private void ToString(StringBuilder sb)
var firstInDictionary =
foreach (var pair in _dictionary)
if (!firstInDictionary)
sb.Append(",");
firstInDictionary =
var value = pair.V
var name = pair.K
if (value is string)
sb.AppendFormat("{0}:\"{1}\"", name, value);
else if (value is IDictionary&string, object&)
new DynamicJsonObject((IDictionary&string, object&)value).ToString(sb);
else if (value is ArrayList)
sb.Append(name + ":[");
var firstInArray =
foreach (var arrayValue in (ArrayList)value)
if (!firstInArray)
sb.Append(",");
firstInArray =
if (arrayValue is IDictionary&string, object&)
new DynamicJsonObject((IDictionary&string, object&)arrayValue).ToString(sb);
else if (arrayValue is string)
sb.AppendFormat("\"{0}\"", arrayValue);
sb.AppendFormat("{0}", arrayValue);
sb.Append("]");
sb.AppendFormat("{0}:{1}", name, value);
sb.Append("}");
public override bool TryGetMember(GetMemberBinder binder, out object result)
if (!_dictionary.TryGetValue(binder.Name, out result))
// return null to avoid exception.
caller can check for null this way...
result = WrapResultObject(result);
public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
if (indexes.Length == 1 && indexes[0] != null)
if (!_dictionary.TryGetValue(indexes[0].ToString(), out result))
// return null to avoid exception.
caller can check for null this way...
result = WrapResultObject(result);
return base.TryGetIndex(binder, indexes, out result);
private static object WrapResultObject(object result)
var dictionary = result as IDictionary&string, object&;
if (dictionary != null)
return new DynamicJsonObject(dictionary);
var arrayList = result as ArrayL
if (arrayList != null && arrayList.Count & 0)
return arrayList[0] is IDictionary&string, object&
? new List&object&(arrayList.Cast&IDictionary&string, object&&().Select(x =& new DynamicJsonObject(x)))
: new List&object&(arrayList.Cast&object&());
#endregion
You can use it like this:
string json = ...;
var serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new[] { new DynamicJsonConverter() });
dynamic obj = serializer.Deserialize(json, typeof(object));
So, given a JSON string:
{ "Name":"Apple", "Price":12.3 },
{ "Name":"Grape", "Price":3.21 }
"Date":"21/11/2010"
The following code will work at runtime:
dynamic data = serializer.Deserialize(json, typeof(object));
data.D // "21/11/2010"
data.Items.C // 2
data.Items[0].N // "Apple"
data.Items[0].P // 12.3 (as a decimal)
data.Items[1].N // "Grape"
data.Items[1].P // 3.21 (as a decimal)
131k76404499
It's pretty simple using :
dynamic stuff = JsonConvert.DeserializeObject("{ 'Name': 'Jon Smith', 'Address': { 'City': 'New York', 'State': 'NY' }, 'Age': 42 }");
string name = stuff.N
string address = stuff.Address.C
Also using Newtonsoft.Json.Linq :
dynamic stuff = JObject.Parse("{ 'Name': 'Jon Smith', 'Address': { 'City': 'New York', 'State': 'NY' }, 'Age': 42 }");
string name = stuff.N
string address = stuff.Address.C
Documentation:
23.1k1482106
You can do this using
- its Decode method returns a dynamic object which you can traverse as you like.
It's included in the System.Web.Helpers assembly (.NET 4.0).
var dynamicObject = Json.Decode(jsonString);
6,12231715
.Net 4.0 has a built-in library to do this:
using System.Web.Script.S
JavaScriptSerializer jss = new JavaScriptSerializer();
var d=jss.Deserialize&dynamic&(str);
This is the simplest way.
2,91011515
Simple "string json data" to object without any third party dll
WebClient client = new WebClient();
string getString = client.DownloadString("/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);
JsonFx can deserialize json into dynamic objects.
20.2k65688
I made a new version of the DynamicJsonConverter that uses Expando Objects.
I used expando objects because I wanted to Serialize the dynamic back into json using Json.net.
using System.C
using System.Collections.G
using System.Collections.ObjectM
using System.D
using System.Web.Script.S
public static class DynamicJson
public static dynamic Parse(string json)
JavaScriptSerializer jss = new JavaScriptSerializer();
jss.RegisterConverters(new JavaScriptConverter[] { new DynamicJsonConverter() });
dynamic glossaryEntry = jss.Deserialize(json, typeof(object))
return glossaryE
class DynamicJsonConverter : JavaScriptConverter
public override object Deserialize(IDictionary&string, object& dictionary, Type type, JavaScriptSerializer serializer)
if (dictionary == null)
throw new ArgumentNullException("dictionary");
var result = ToExpando(dictionary);
return type == typeof(object) ? result :
private static ExpandoObject ToExpando(IDictionary&string, object& dictionary)
var result = new ExpandoObject();
var dic = result as IDictionary&String, object&;
foreach (var item in dictionary)
var valueAsDic = item.Value as IDictionary&string, object&;
if (valueAsDic != null)
dic.Add(item.Key, ToExpando(valueAsDic));
var arrayList = item.Value as ArrayL
if (arrayList != null && arrayList.Count & 0)
dic.Add(item.Key, ToExpando(arrayList));
dic.Add(item.Key, item.Value);
private static ArrayList ToExpando(ArrayList obj)
ArrayList result = new ArrayList();
foreach (var item in obj)
var valueAsDic = item as IDictionary&string, object&;
if (valueAsDic != null)
result.Add(ToExpando(valueAsDic));
var arrayList = item as ArrayL
if (arrayList != null && arrayList.Count & 0)
result.Add(ToExpando(arrayList));
result.Add(item);
public override IDictionary&string, object& Serialize(object obj, JavaScriptSerializer serializer)
throw new NotImplementedException();
public override IEnumerable&Type& SupportedTypes
get { return new ReadOnlyCollection&Type&(new List&Type&(new[] { typeof(object) })); }
Nikhil Kothari .
He included a
which provides a dynamic implementation of a REST client, which works on JSON data.
He also has a
that works off strings of JSON data directly.
401k388101132
Simplest way is
Just include this
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.
Another way using :
dynamic stuff = Newtonsoft.Json.JsonConvert.DeserializeObject("{ color: 'red', value: 5 }");
string color = stuff.
int value = stuff.
You can extend the JavaScriptSerializer to recursively copy the dictionary it created to expando object(s) and then use them dynamically:
static class JavaScriptSerializerExtensions
public static dynamic DeserializeDynamic(this JavaScriptSerializer serializer, string value)
var dictionary = serializer.Deserialize&IDictionary&string, object&&(value);
return GetExpando(dictionary);
private static ExpandoObject GetExpando(IDictionary&string, object& dictionary)
var expando = (IDictionary&string, object&)new ExpandoObject();
foreach (var item in dictionary)
var innerDictionary = item.Value as IDictionary&string, object&;
if (innerDictionary != null)
expando.Add(item.Key, GetExpando(innerDictionary));
expando.Add(item.Key, item.Value);
return (ExpandoObject)
Then you just need to having a using statement for the namespace you defined the extension in (consider just defining them in System.Web.Script.Serialization... another trick is to not use a namespace, then you don't need the using statement at all) and you can consume them like so:
var serializer = new JavaScriptSerializer();
var value = serializer.DeserializeDynamic("{ 'Name': 'Jon Smith', 'Address': { 'City': 'New York', 'State': 'NY' }, 'Age': 42 }");
var name = (string)value.N // Jon Smith
var age = (int)value.A
var address = value.A
var city = (string)address.C
// New York
var state = (string)address.S // NY
I am using like this in my code and it's working fine
using System.Web.Script.S
JavaScriptSerializer oJS = new JavaScriptSerializer();
RootObject oRootObject = new RootObject();
oRootObject = oJS.Deserialize&RootObject&(Your JSon String);
For that I would use JSON.NET to do the low-level parsing of the JSON stream and then build up the object hierarchy out of instances of the ExpandoObject class.
81.2k27161240
Deserializing in JSON.NET can be dynamic using the JObject class, which is included in that library.
My JSON string represents these classes:
public class Foo {
public int Age {}
public Bar Bar {}
public class Bar {
public DateTime BDay {}
Now we deserialize the string WITHOUT referencing the above classes:
var dyn = JsonConvert.DeserializeObject&JObject&(jsonAsFooString);
JProperty propAge = dyn.Properties().FirstOrDefault(i=&i.Name == "Age");
if(propAge != null) {
int age = int.Parse(propAge.Value.ToString());
Console.WriteLine("age=" + age);
//or as a one-liner:
int myage = int.Parse(dyn.Properties().First(i=&i.Name == "Age").Value.ToString());
Or if you want to go deeper:
var propBar = dyn.Properties().FirstOrDefault(i=&i.Name == "Bar");
if(propBar != null) {
JObject o = (JObject)propBar.First();
var propBDay = o.Properties().FirstOrDefault (i =& i.Name=="BDay");
if(propBDay != null) {
DateTime bday = DateTime.Parse(propBDay.Value.ToString());
Console.WriteLine("birthday=" + bday.ToString("MM/dd/yyyy"));
//or as a one-liner:
DateTime mybday = DateTime.Parse(((JObject)dyn.Properties().First(i=&i.Name == "Bar").First()).Properties().First(i=&i.Name == "BDay").Value.ToString());
for a complete example.
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.
There is a lightweight json library for C# called SimpleJson which can be found at
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
5,75112243
use DataSet(C#) With javascript
simple function for create json stream with DataSet input
create json like(multi table dataset)
[[{a:1,b:2,c:3},{a:3,b:5,c:6}],[{a:23,b:45,c:35},{a:58,b:59,c:45}]]
just client side use eval for example
var d=eval('[[{a:1,b:2,c:3},{a:3,b:5,c:6}],[{a:23,b:45,c:35},{a:58,b:59,c:45}]]')
d[0][0].a //out 1 from table 0 row 0
d[1][1].b //out 59 from table 1 row 1
//create by Behnam Mohammadi And Saeed Ahmadian
public string jsonMini(DataSet ds)
int t=0, r=0, c=0;
string stream = "[";
for (t = 0; t & ds.Tables.C t++)
stream += "[";
for (r = 0; r & ds.Tables[t].Rows.C r++)
stream += "{";
for (c = 0; c & ds.Tables[t].Columns.C c++)
stream += ds.Tables[t].Columns[c].ToString() + ":'" + ds.Tables[t].Rows[r][c].ToString() + "',";
stream = stream.Substring(0, stream.Length - 1);
stream += "},";
stream = stream.Substring(0, stream.Length - 1);
stream += "],";
stream = stream.Substring(0, stream.Length - 1);
stream += "];";
2,85611218
To get an ExpandoObject:
using Newtonsoft.J
using Newtonsoft.Json.C
Container container = JsonConvert.Deserialize&Container&(jsonAsString, new ExpandoObjectConverter());
try this -
var units = new { Name = "Phone", Color= "White" };
var jsonResponse = JsonConvert.DeserializeAnonymousType(json, units );
Look at the article I wrote on CodeProject, one that answers the question precisely:
There is way too much for re-posting it all here, and even less point since that article has an attachment with the key/required source file.
3,97212137
Your Answer
Sign up or
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Post as a guest
By posting your answer, you agree to the
Not the answer you're looking for?
Browse other questions tagged
Stack Overflow works best with JavaScript enabled

我要回帖

更多关于 半条命2 的文章

 

随机推荐