Categories
Uncategorized

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 replies on “Quick JSON Parsing with C#”

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

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

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


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 🙂
 

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
}

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

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

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

Thanks
Quran

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

 

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?

@ .net beginnen,

you would just call:

Console.WriteLine(“Age: “+o[“age”]);”

 

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?

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.

Great example! Thanks for sharing.

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

Thanks,

Juliana

 

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.

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

Hi.

i want to convert json http url to excel file.

please help me with the codes.

 

Thankyou 🙂

Suppose this is my JSON Data Received through API..

after this I created a class RootObject…

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

//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
}

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

Comments are closed.