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.

4 upvote
  flag
If you want something 'dynamic', why not just use the get-style accessors that come with most JSON decoders that don't go to plain-old-object? (e.g. is there really a need for 'dynamic' object creation?) json.org has a bunch of links for C# JSON implementations. – user166390
upvote
  flag
I'm working on a project that is trying to keep external dependencies to a minimum. So if it's possible to something with the stock .net serializers and types that would be preferred. Of course if it's not possible I'm hitting up json.org. Thanks! – jswanson
28 upvote
  flag
I'm really surprised the C# team added 'dynamic' but then there is no way in the CLR to convert a JSON object to a dynamic CLR class instance. – Frank Schwieterman
2 upvote
  flag
Unfortunately the accepted answer doesn't work in .NET 4 RTM. I posted an answer that helped me get going with this which might be useful to others. – Drew Noakes
upvote
  flag
(Although it appears that Newtonsoft JSON.NET comes pretty close. There aren't any really good examples, though.) – Hot Licks

21 Answers 11

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.

up vote 527 down vote accepted

If you are happy to have a dependency upon the System.Web.Helpers assembly, then you can use the Json class:

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 here. 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;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;

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) : null;
    }

    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> _dictionary;

        public DynamicJsonObject(IDictionary<string, object> dictionary)
        {
            if (dictionary == null)
                throw new ArgumentNullException("dictionary");
            _dictionary = dictionary;
        }

        public override string ToString()
        {
            var sb = new StringBuilder("{");
            ToString(sb);
            return sb.ToString();
        }

        private void ToString(StringBuilder sb)
        {
            var firstInDictionary = true;
            foreach (var pair in _dictionary)
            {
                if (!firstInDictionary)
                    sb.Append(",");
                firstInDictionary = false;
                var value = pair.Value;
                var name = pair.Key;
                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 = true;
                    foreach (var arrayValue in (ArrayList)value)
                    {
                        if (!firstInArray)
                            sb.Append(",");
                        firstInArray = false;
                        if (arrayValue is IDictionary<string, object>)
                            new DynamicJsonObject((IDictionary<string, object>)arrayValue).ToString(sb);
                        else if (arrayValue is string)
                            sb.AppendFormat("\"{0}\"", arrayValue);
                        else
                            sb.AppendFormat("{0}", arrayValue);

                    }
                    sb.Append("]");
                }
                else
                {
                    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 = null;
                return true;
            }

            result = WrapResultObject(result);
            return true;
        }

        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 = null;
                    return true;
                }

                result = WrapResultObject(result);
                return true;
            }

            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 ArrayList;
            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>());
            }

            return result;
        }
    }

    #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:

{
  "Items":[
    { "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.Date; // "21/11/2010"
data.Items.Count; // 2
data.Items[0].Name; // "Apple"
data.Items[0].Price; // 12.3 (as a decimal)
data.Items[1].Name; // "Grape"
data.Items[1].Price; // 3.21 (as a decimal)
upvote
  flag
Thanks Drew, your TryGetMember sorted my issue around recursing into nested collections, but could you perhaps let us know what it is that makes it work. Is it in the fact that array lists are cast into IDictionary and then projected as DynamicJsonObjects, rather than being projected as arrayList members? Hope this isn't a too dumb question. Thanks for the answer :) – Mark Dickinson
upvote
  flag
@Mark, it's been a while since I looked at this but from memory what you're describing sounds right. – Drew Noakes
1 upvote
  flag
I get an error in dynamic obj = serializer.Deserialize(json, typeof(object)); saying that no overload for method with 2 arguments..wrong dll or what? – Stewie Griffin
upvote
  flag
@Stewie, the type I'm using is System.Web.Script.Serialization.JavaScriptSerializer which is in version 4.0.0.0 of System.Web.dll. – Drew Noakes
upvote
  flag
System.Web.Script.Serialization.JavaScriptSerializer is in System.Web.Extensions.dll - goo.gl/8zRrj – Rush Frisby
upvote
  flag
@rushonerok, you're absolutely right. – Drew Noakes
1 upvote
  flag
I found that your ToString method wasn't working for me, so I rewrote it. It might have some bugs, but it's working over my dataset, so I'll provide it here for anyone else who might be having trouble with this: pastebin.com/BiRmQZdz – Quantumplation
upvote
  flag
Is this possible in VB.NET? – Timuçin
upvote
  flag
@Tim, I can't see why not, but I'm not familiar enough with VB.NET to convert the code for you. You could compile the C# code and use it via an assembly reference, or try to convert it yourself. I don't think it would be too hard to convert. – Drew Noakes
upvote
  flag
Yes, I already used the c# assembly, but it is still the same. This "dynamic" object detection didnt work. In my case, "data" is an array of Objects that each of them includes key-value pair for json data. – Timuçin
19 upvote
  flag
You can use System.Web.Helpers.Json - it offers a Decode method that returns a dynamic object. I've also posted this info as an answer. – Vlad
upvote
  flag
can't parse this string: (not sure you can visit this) dropbox.com/s/aefohe97t3aq81y/json-data.txt – Cooper.Wu
2 upvote
  flag
This helped me a lot as well, but I'm curious what I should do if I need to use the .Serialize method, which currently only throws a NotImplementedException... I'm not too familiar with sealed classes and/or extended abstract classes. Can anyone point me in the right direction? – Cory W.
2 upvote
  flag
sometimes in js you have fields with special chars like "background-color". To access such fields in js you do obj["background-color"]. How can I access such fields from c# after deserializing to dynamic object? I can't do obj.background-color, of course, and obj["background-color"] doesn't seem to work. It would be nice if the dynamic object could also be accessed as a dictionary, at the same time, exactly like in js. – Radu Simionescu
upvote
  flag
@RaduSimionescu, have you tried swapping the hyphen for an underscore? I haven't tried it myself, but I recall something somewhere about this. – Drew Noakes
upvote
  flag
@DrewNoakes thanks for the class a lot. Could you specify in your answer that "Dynamic View" doesn't work with your class? For me it was unexpected behavior - at first I thought that your class doesn't work at all. – Seekeer
upvote
  flag
@Seeker, I'm not sure exactly what you mean by 'dynamic view'. – Drew Noakes
2 upvote
  flag
@RaduSimionescu I am probably a bit late, but maybe this helps future visitors. I had the same problem, just with the field-name params (which is a keyword in C#). In addition to TryGetMember you can override TryGetIndex, which gives you exactly the same behavior as in JS. Then you can do obj["params"] or obj["background-color"] for awkward field names. – Martin Ender
1 upvote
  flag
@m.buettner, I haven't tried this myself, but you can work around some keyword clashes in C# by prefixing with an @ character. For example, the following is valid C#: string @class = "MyClass"; – Drew Noakes
upvote
  flag
@DrewNoakes huh, good to know - I might actually use that in my case. But it doesn't solve the hyphen problem, I guess. – Martin Ender
upvote
  flag
Won't work on MVC 5, see Tom Peplow Answer. – Ronen Festinger
upvote
  flag
System.Web.Helpers could be downloaded in VS2015 using Package Manage Console with this command: Install-Package System-Web-Helpers.dll Also, Json in System.Web.Mvc conflicts with Json in System.Web.Helpers. So you can use dynamic data = System.Web.Helpers.Json.Decode(myJSONString); – Mahesh
upvote
  flag
Is there any cost involved with this rather than using individual classes? – Dhanashree
upvote
  flag
Where do we get the System.Web.Helpers dll from? The article you have pointed to doesn't have an aswer. – Melbourne Developer
upvote
  flag
@MelbourneDeveloper take a look here //allinonescript.com/q/8037895/24874 – Drew Noakes
upvote
  flag
I already looked at that. There is no answer. @DrewNoakes – Melbourne Developer

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.

JsonFx can deserialize json into dynamic objects.

https://github.com/jsonfx/jsonfx

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

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;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Dynamic;
using System.Web.Script.Serialization;

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)) as dynamic;
        return glossaryEntry;
    }

    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 : null;
        }

        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));
                    continue;
                }
                var arrayList = item.Value as ArrayList;
                if (arrayList != null && arrayList.Count > 0)
                {
                    dic.Add(item.Key, ToExpando(arrayList));
                    continue;
                }

                dic.Add(item.Key, item.Value);
            }
            return result;
        }

        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));
                    continue;
                }

                var arrayList = item as ArrayList;
                if (arrayList != null && arrayList.Count > 0)
                {
                    result.Add(ToExpando(arrayList));
                    continue;
                }

                result.Add(item);
            }
            return result;
        }

        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) })); }
        }
    }
}  

.Net 4.0 has a built-in library to do this:

using System.Web.Script.Serialization;
JavaScriptSerializer jss = new JavaScriptSerializer();
var d=jss.Deserialize<dynamic>(str);

This is the simplest way.

upvote
  flag
Most of the previous answers came before .NET 4.0 RTM. – jswanson
25 upvote
  flag
have you tried this? It returns Dictionary<string,object>. Unless I'm missing something, your example does not return a dynamic object. – sergiopereira
upvote
  flag
@sergiopereira yes I did. you can cast any type to dynamic type. so why not just do a cast? – Peter Long
16 upvote
  flag
This doesn't work, it just return a dict in the form of a dynamic – mattmanser
upvote
  flag
@mattmanser, please learn what is dynamic. every dynamic type would be resolved to a static type finally. – Peter Long
53 upvote
  flag
@Peter Long I believe I have failed to state my case clearly, dear fellow. Let me attempt to rectify my error. I know what a dynamic is. This doesn't allow you to pass in a JSON object and use d.code, you'd have to do d["code"].Value, which isn't what most people finding this answer want, we already know how to get the dictionary and casting it to a dynamic is a total waste of time. I respectfully disagree, sir. – mattmanser
15 upvote
  flag
@mattmanser...I already wasted those minutes trying his code cus I didn't read the comments or scrolled down :( – Shawn Mclean
upvote
  flag
@mattmanser, I really don't understand you. my answer was picked as the best answer. Please think who is wrong. – Peter Long
4 upvote
  flag
@mattmanser, we already know how to get the dictionary and casting it to a dynamic. It does not have to be a dictionay. Json also have lists besides dictionary. And also lists and dictionaries could be nested. My code could handle all of these situations. BUT your method can NOT. – Peter Long
upvote
  flag
@mattmanser, instead of d["code"].Value, you want d.code. As far as I know, it is impossible(or meaningless). Think of dynamic as deferring part of the compiler’s job to runtime. That's what dynamic is useful for. Dynamic is not mean to solve your problem. – Peter Long
upvote
  flag
@mattmanser is tripping - this works beautifully - thanks peter +1 – Fraser
upvote
  flag
Thank you Peter, this was precisely what I needed! – Anders
upvote
  flag
this is simple and direct-to-the-point answer...**and it works**. While there are 3rd party libraries that are more full-featured and more efficient (ServiceStack comes to mind, NOT the overrated and super-bloated JSON.NET libraries), sometimes it's better to have the native option (which is available since .NET 4.x) if you don't necessarily need the speed...also, @mattmanser is wrong on all counts; he doesn't seem to grasp what dynamic types are at the time he posted his comments. – Dexter Legaspi
4 upvote
  flag
@mattmanser is right; it is possible to implement IDynamicMetaObjectProvider (or use e.g. ExpandoObject) that is able to intercept properties and look them up in an internal dictionary. This combined with the use of dynamic allows code such as d.code to be used. It's kind of pointless to cast a dictionary to a dynamic. – Stephen Drew
1 upvote
  flag
I upvoted this answer even though the answer doesnt strictly return a IDynamicMetaObjectProvider object. I mean it's useful for people who dont strictly want it to be dynamic. The OP states he wants to avoid creating custom classes and attributes and this answer helps. Peter Long could have been more clear about that in his answer, though. Can I edit this answer? – nawfal

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));
            }
            else
            {
                expando.Add(item.Key, item.Value);
            }
        }

        return (ExpandoObject)expando;
    }
}

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.Name; // Jon Smith
var age = (int)value.Age;      // 42

var address = value.Address;
var city = (string)address.City;   // New York
var state = (string)address.State; // NY

It's pretty simple using Json.NET:

dynamic stuff = JsonConvert.DeserializeObject("{ 'Name': 'Jon Smith', 'Address': { 'City': 'New York', 'State': 'NY' }, 'Age': 42 }");

string name = stuff.Name;
string address = stuff.Address.City;

Also using Newtonsoft.Json.Linq :

dynamic stuff = JObject.Parse("{ 'Name': 'Jon Smith', 'Address': { 'City': 'New York', 'State': 'NY' }, 'Age': 42 }");

string name = stuff.Name;
string address = stuff.Address.City;

Documentation: Querying JSON with dynamic

1 upvote
  flag
Interesting, using MVC, how do I bind this to the view? I read through a few posts about dynamic or anonymous type bind, but I'm not seeing an example of how to use it. Say I have json that may have a lot of layers. – Vyache
upvote
  flag
How can you introspect the dynamic stuff? – Hot Licks
4 upvote
  flag
@HotLicks: To introspect the dynamic stuff do something like: foreach (Newtonsoft.Json.Linq.JProperty jproperty in stuff) { Console.WriteLine("jproperty.Name = {0}", jproperty.Name);} – Matthias
7 upvote
  flag
What's the difference between JsonConvert.DeserializeObject and JObject.Parse ? The answer is using them both in the same way to do the same thing but doesn't explain the difference. – cja
1 upvote
  flag
@TomPeplow Tried this. It didn't work for me. It says that "JObject doesn't implement 'Name'". – Lee Louviere
2 upvote
  flag
upvote
  flag
I can't get this to work. I've narrowed the issue down to being inside an async method. If I make the method synchronous it works as expected. However, make the method async and I can't get a dynamic, I just get an object. Explicit casting does nothing, still just gives me an object. Is anyone else experiencing this? – codeConcussion
upvote
  flag
Are there any side effects, i mean on performance? As i see Json.Net claims it is fast as compared to other's two newtonsoft.com/json but when we use dynamic object... will performance stays the same? – Atta H.
upvote
  flag
Can’t understand what I am doing wrong. In mono environment dynamic objects are not deserialized and it samestring, but if you pass the specific type it will deserialized . What I am missing? – PEO
upvote
  flag
@codeConcussion It is possible some people having issues are missing a reference to Microsoft.CSharp? dynamic requires this reference (as does async -- I might be wrong there) – Michael Blackburn

You can do this using System.Web.Helpers.Json - 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);
25 upvote
  flag
FYI System.Web.Helpers.dll requires .net 4.0 but is not included in .net 4.0. It can be installed with ASP.NET MVC 3 – jbtule
7 upvote
  flag
You will find this assembly in the Extensions group under Assemblies in Visual Studio 2012 – W3Max
1 upvote
  flag
Any Issues with using dynamic ? How can we handle exceptions efficiently if input JSON does not contain the properties.. – Usama Khalil
5 upvote
  flag
If you're wanting to strongly type the model then be sure to use the Json.Decode<T>(string) method. – Mike
2 upvote
  flag
To add this library to your project: //allinonescript.com/questions/8037895/… – user565869

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);
3 upvote
  flag
Id don't get it. This is by far most simple solution and nobody mentions it. – cikatomo
1 upvote
  flag
yes it's simple :) sometime you need serialize but don't want to include 3rd part dll – İbrahim Özbölük
upvote
  flag
Can you elaborate on : how dynamic can access the DEserialized object via : myObject["myprop"] ? I know it's done on runtime but how accessing it via myObject["myprop"] is valid ? – Royi Namir
1 upvote
  flag
You can deserialize your object like Personel item = serializer.Deserialize<Personel>(getString); and if you use dynamic object also you can using array and everything is possible like everyobject – İbrahim Özbölük

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.

Another way using Newtonsoft.Json:

dynamic stuff = Newtonsoft.Json.JsonConvert.DeserializeObject("{ color: 'red', value: 5 }");
string color = stuff.color;
int value = stuff.value;

Look at the article I wrote on CodeProject, one that answers the question precisely:

Dynamic types with JSON.NET

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.

10 upvote
  flag
Take a look at //allinonescript.com/questions/how-to-answer: Provide context for links A link to a potential solution is always welcome, but please add context around the link so your fellow users will have some idea what it is and why it’s there – jAC

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}]]')

then use

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.Count; t++)
    {
        stream += "[";
        for (r = 0; r < ds.Tables[t].Rows.Count; r++)
        {
            stream += "{";
            for (c = 0; c < ds.Tables[t].Columns.Count; c++)
            {
                stream += ds.Tables[t].Columns[c].ToString() + ":'" + ds.Tables[t].Rows[r][c].ToString() + "',";
            }
            if(c>0)
                stream = stream.Substring(0, stream.Length - 1);
            stream += "},";
        }
        if(r>0)
            stream = stream.Substring(0, stream.Length - 1);
        stream += "],";
    }
    if(t>0)
        stream = stream.Substring(0, stream.Length - 1);
    stream += "];";
    return stream;
}

To get an ExpandoObject:

using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

Container container = JsonConvert.Deserialize<Container>(jsonAsString, new ExpandoObjectConverter());

try this -

  var units = new { Name = "Phone", Color= "White" };
    var jsonResponse = JsonConvert.DeserializeAnonymousType(json, units );

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 {get;set;}
   public Bar Bar {get;set;}
}

public class Bar {
   public DateTime BDay {get;set;}
}

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());

See post for a complete example.

I am using like this in my code and it's working fine

using System.Web.Script.Serialization;
JavaScriptSerializer oJS = new JavaScriptSerializer();
RootObject oRootObject = new RootObject();
oRootObject = oJS.Deserialize<RootObject>(Your JSon String);
1 upvote
  flag
but that's not what the question is asking about. there's a different when you have to specify the type for every json string and working with dynamic type. – Illuminati

I use: http://json2csharp.com/ to get A class representing the Json Object.

Input:

{
   "name":"John",
   "age":31,
   "city":"New York",
   "Childs":[
      {
         "name":"Jim",
         "age":11
      },
      {
         "name":"Tim",
         "age":9
      }
   ]
}

Output:

public class Child
{
    public string name { get; set; }
    public int age { get; set; }
}

public class Person
{
    public string name { get; set; }
    public int age { get; set; }
    public string city { get; set; }
    public List<Child> Childs { get; set; }
}

After that I use Newtonsoft.Json to fill the Class:

using Newtonsoft.Json;

namespace GitRepositoryCreator.Common
{
    class JObjects
    {
        public static string Get(object p_object)
        {
            return JsonConvert.SerializeObject(p_object);
        }
        internal static T Get<T>(string p_object)
        {
            return JsonConvert.DeserializeObject<T>(p_object);
        }
    }
}

You can call it like that:

Person jsonClass = JObjects.Get<Person>(stringJson);

string stringJson = JObjects.Get(jsonClass);

PS:

If your json variable name is no valid C# name (name starts with $) you can fix that like this:

public class Exception
{
   [JsonProperty(PropertyName = "$id")]
   public string id { get; set; }
   public object innerException { get; set; }
   public string message { get; set; }
   public string typeName { get; set; }
   public string typeKey { get; set; }
   public int errorCode { get; set; }
   public int eventId { get; set; }
}

You can use using Newtonsoft.Json

var jRoot = 
 JsonConvert.DeserializeObject<dynamic>(Encoding.UTF8.GetString(resolvedEvent.Event.Data));

resolvedEvent.Event.Data is my response getting from calling core Event .

Not the answer you're looking for? Browse other questions tagged or ask your own question.