Quick JSON Parsing with C#

It’s quite sad that Microsoft doesn’t ship a decent JSON parser with .NET, not even the latest .NET 4. If we look at the web, everyone uses JSON today. Without no out of the box support for JSON, I was having much troubles consuming different APIs Services. But just a few moments ago, I found the JSON.NET project on CodePlex. The library has cool Linq integration that makes JSON parsing easier.

For test purposes, I am outputting this JSON string on http://localhost/json.php :

After downloading the JSON.NET package, I added a reference to “Newtonsoft.Json.dll”. Then used the following code snippet (C#) to parse the data and print the values from a console app:


30 Comments Quick JSON Parsing with C#

  1. Pavan

    Hello Masnun ,
    Your post is helpful. I was wondering whether you have any idea of how to parse the data to a .csv file is a formatted way ?

    After parse the json object , I write it to a text file using streamwriter. So in this I have big list of JSON format information, But I want this to be in a formatted way as .csv format or arragned according to the field name. If you have any idea, please through some light .

    Thanks,
    Pavan

    Reply
    1. maSnun

      Hi Pavan,

      I am not aware of any CSV writer but I bet there is a good number of them in the wild. Please search in Google, I hope you shall find one.

      Thanks

      Reply
      1. vish

        Hello Sir ,
        I use the the code but i got Error
        “unexpected character encountered while parsing value m. path ” line 0 position 0″
        I publish my web services on Local IIS

        Reply
    2. chandni


      hi. i want the same thing. if you can help me out please? i have json http links wich needed to be downloaded automatically to csv or excel format.
      how to start? thankyou 🙂
       

      Reply
      1. Rugnir

        Hi there Chandi. If you are still around, I can help you with this. Simply write to a file yourself with a System.IO.StreamWriter.

        something a little like this

        System.IO.StreamWriter file = new System.IO.StreamWriter(path);
        string line = "";
        char[] delimiterChars = { ',' };
        for (int x=0;x<values.Count;x++)
        {
        file.WriteLine(values[x]);
        // Stuff
        }

        Reply
  2. sanjaya verma

    Try it ….this is working well…..

    // Serialization of DataSet to json string

    StringWriter sw = new StringWriter();
    versionUpGetData.WriteXml(sw, XmlWriteMode.WriteSchema);
    XmlDocument xd = new XmlDocument();
    xd.LoadXml(sw.ToString());
    String jsonText = JsonConvert.SerializeXmlNode(xd);
    File.WriteAllText(“d:/datasetJson.txt”,jsonText);

    //Deserialization of Json String to DataSet

    XmlDocument xd1 = new XmlDocument();
    xd1 = (XmlDocument)JsonConvert.DeserializeXmlNode(jsonText);
    DataSet jsonDataSet = new DataSet();
    jsonDataSet.ReadXml(new XmlNodeReader(xd1));

    Reply
  3. .net beginnen

    very intersted blog, thank you fot that!

    actually I’m still a question abou this. have you a solution for this format of json:
    {
    “name”: name,
    “adress”: “adress”,
    “birthsday”: “01-01-1977”
    “more_data”: {
    “gender”: “man”
    “age”: “33”
    }
    }

    how will ” Console.WriteLine(“Name: “+o[“name”]);” look like for the age.

    thank you man

    Reply
  4. Quran

    Very useful, I did find any solution in .Net framework on how to parse Json, now I can use this library,

    Thanks
    Quran

    Reply
  5. shankar

    I cannot access the namespace for the Json… I think it is not supported in my version. so pls help me to find the solution

     

    Reply
  6. Ryan

    I’m working with json.net as you mentioned, and thanks for the tutorial.  It works fine on localhost, but when I attempt to deploy it on my IIS server it states that the assembly or references is missing.  Any ideas?

    Reply
  7. Anon

    I found your blog/website really beautiful, but this post, although old, is misleading: there actually is a standard way to parse JSON with C#, with the API provided by Microsoft.

    It is the JavaScriptSerializer Class and it exists since the version 3.5 of the .NET framework. Maybe you could find time to correct your article so it reflects that fact?

    Reply
  8. Sebastian Esp

    Very helpful, i’ve been looking for a simple example of how to do this for a while, and yours explained it perfectly. Kudos to you sir.

    Reply
  9. Juliana Cordeiro

    Great example! Thanks for sharing.

    Do you have an example that does the opposite? that means, that writes the json url?

    Thanks,

    Juliana

     

    Reply
  10. Martin

    Thanks for this!

    A question though, if I have this Json

    How can I get the value of property1, I tried just using property1 in the code but it does not show the value, just a blank space.

    Reply
    1. Francis

      o produces an array on complex types. so you can:

      dynamic Data = o.Data;

      dynamic DeviceList = Data.Devices;

      foreach (var item in DeviceList)
      {
      COnsole.writeline(item[“property1”]);
      }

      Reply
  11. akg

    Suppose this is my JSON Data Received through API..

    after this I created a class RootObject…

    Reply
  12. VV

    Thanks for the link

     

    Can you also please let me know how to get length or an element where its an array?

     

    So in your example: “email” has two elements.

     

     

    Similar to object.lenght

     

    Thanks,

    VV

    Reply
  13. Pingback: JSON in C# – SAIFUL DIARY

  14. Pär Eriksson

    //install https://www.nuget.org/packages/Newtonsoft.Json
    //using https://docs.nuget.org/consume/package-manager-console

    WebClient webclient = new WebClient();
    String stringJsonData =webclient.DownloadString(“http://www.omdbapi.com/?s=Batman”);//get all the Batman movies as JSON string
    JObject jsonobject= JObject.Parse(stringJsonData);
    JToken arr = jsonobject[“Search”];//get the JTokem of Search, the json array that contains all the batman movies
    //loop each token(movie) in search array
    foreach(JToken tokenmovie in arr)
    {
    Console.WriteLine(tokenmovie[“Title”]);//print the title for each batman movie
    Console.WriteLine(tokenmovie[“Year”]);///print the year when the batman movie was released
    }

    Reply
  15. Jorge Eduardo

    Your post es awesome.  Thanks for your generosity.  How about adding the way to display data in a WPF page?  Thanks,  Jorge Eduardo.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *