249

Trying to convert a JSON string into an object in C#. Using a really simple test case:

JavaScriptSerializer json_serializer = new JavaScriptSerializer();
object routes_list = json_serializer.DeserializeObject("{ \"test\":\"some data\" }");

The problem is that routes_list never gets set; it's an undefined object. Any ideas?

Cloudy
7,5297 gold badges64 silver badges98 bronze badges
asked Jan 6, 2011 at 1:38
6
  • 1
    @Greg: I actually recommend the JavaScriptSerializer over MS's version as it won't accept anything else but WCF's custom JSON formatting (e.g. date fields that look like dates but aren't surrounded in DATE() fail miserably) Commented Jan 6, 2011 at 1:50
  • Also, look at this Parsing JSON objects with JavascriptSerializer in .NET article, which is actually a great tutorial. Commented Oct 23, 2012 at 17:50
  • 1
    Where are you getting JavaScriptSerializer? It is unrecognized in my C# .NET 3.5 project. Commented Oct 15, 2013 at 20:47
  • 1
    @B. Clay Shannon This resolved it for me stackoverflow.com/questions/7000811/… Commented Feb 27, 2015 at 18:05
  • You can use JavaScriptSerializer for this purpose without any issues.I will provide answer below . Commented Nov 21, 2020 at 3:03

17 Answers 17

320

You can use the Newtonsoft.Json library as follows:

using Newtonsoft.Json;
...
var result = JsonConvert.DeserializeObject<T>(json);

Where T is your object type that matches your JSON string.

TylerH
21.2k83 gold badges83 silver badges120 bronze badges
answered Feb 15, 2013 at 22:04

1 Comment

The "T" type class you end up creating can be partial and doesn't need to be an exact copy of the full response that includes every JSON property. You can de-serialize exactly what you need although the hierarchy needs to match.
141

It looks like you're trying to deserialize to a raw object. You could create a Class that represents the object that you're converting to. This would be most useful in cases where you're dealing with larger objects or JSON Strings.

For instance:

 class Test {
 String test; 
 String getTest() { return test; }
 void setTest(String test) { this.test = test; }
 }

Then your deserialization code would be:

 JavaScriptSerializer json_serializer = new JavaScriptSerializer();
 Test routes_list = 
 (Test)json_serializer.DeserializeObject("{ \"test\":\"some data\" }");

More information can be found in this tutorial: http://www.codeproject.com/Tips/79435/Deserialize-JSON-with-Csharp.aspx

Mattiavelli
8962 gold badges9 silver badges23 bronze badges
answered Jan 6, 2011 at 1:53

5 Comments

But in pointed article autoproperties are used. It's worth mentioning too.
Sorry, but this code sample does not work. DeserializeObject gives an exception. Use var routes_list = serializer.Deserialize<Test>("{\"test\":\"some data\"}"); instead. Also, you don't need get/setTest( ), and String test, should be public. This looks more like java than C#.
as Dan Vallejo mentioned, this is an incorrect solution. After all, setTest(String test) is not returning, which is compile error as well.
Can also use this : json_serializer.Deserialize<Test>("{ \"test\":\"some data\" }"); //instead of (Test)json_serializer.....
If you are unsure of the format for your class object, try this link. It translates your Json string into the right classes. Saved me a ton of time!
60

You probably don't want to just declare routes_list as an object type. It doesn't have a .test property, so you really aren't going to get a nice object back. This is one of those places where you would be better off defining a class or a struct, or make use of the dynamic keyword.

If you really want this code to work as you have it, you'll need to know that the object returned by DeserializeObject is a generic dictionary of string,object. Here's the code to do it that way:

var json_serializer = new JavaScriptSerializer();
var routes_list = (IDictionary<string, object>)json_serializer.DeserializeObject("{ \"test\":\"some data\" }");
Console.WriteLine(routes_list["test"]);

If you want to use the dynamic keyword, you can read how here.

If you declare a class or struct, you can call Deserialize instead of DeserializeObject like so:

class MyProgram {
 struct MyObj {
 public string test { get; set; }
 }
 static void Main(string[] args) {
 var json_serializer = new JavaScriptSerializer();
 MyObj routes_list = json_serializer.Deserialize<MyObj>("{ \"test\":\"some data\" }");
 Console.WriteLine(routes_list.test);
 Console.WriteLine("Done...");
 Console.ReadKey(true);
 }
}
answered Jan 6, 2011 at 1:51

2 Comments

Doing: json_serializer = new JavaScriptSerializer(); object routes_list = (IDictionary<string, object>)json_serializer.DeserializeObject("{ \"test\":\"some data here\" }"); Still getting 'routes_list' does not exist in the current context.
Don't use object routes_list. Use var or explicitly repeat yourself and declare routes_list as an IDictionary<string,object>.
36

Using dynamic object with JavaScriptSerializer.

JavaScriptSerializer serializer = new JavaScriptSerializer(); 
dynamic item = serializer.Deserialize<object>("{ \"test\":\"some data\" }");
string test= item["test"];
//test Result = "some data"
answered Apr 16, 2013 at 11:51

1 Comment

How will you find key in hierarchy of classes?
20

Newtonsoft is faster than java script serializer. ... this one depends on the Newtonsoft NuGet package, which is popular and better than the default serializer.

one line code solution.

var myclass = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(Jsonstring);
Myclass oMyclass = Newtonsoft.Json.JsonConvert.DeserializeObject<Myclass>(Jsonstring);
answered Jan 21, 2015 at 7:41

Comments

20

You can accomplished your requirement easily by using Newtonsoft.Json library. I am writing down the one example below have a look into it.

Class for the type of object you receive:

public class User
{
 public int ID { get; set; }
 public string Name { get; set; }
}

Code:

static void Main(string[] args)
{
 string json = "{\"ID\": 1, \"Name\": \"Abdullah\"}";
 User user = JsonConvert.DeserializeObject<User>(json);
 Console.ReadKey();
}

this is a very simple way to parse your json.

answered Jun 17, 2015 at 12:14

Comments

16

Here's a simple class I cobbled together from various posts.... It's been tested for about 15 minutes, but seems to work for my purposes. It uses JavascriptSerializer to do the work, which can be referenced in your app using the info detailed in this post.

The below code can be run in LinqPad to test it out by:

  • Right clicking on your script tab in LinqPad, and choosing "Query Properties"
  • Referencing the "System.Web.Extensions.dll" in "Additional References"
  • Adding an "Additional Namespace Imports" of "System.Web.Script.Serialization".

Hope it helps!

void Main()
{
 string json = @"
 {
 'glossary': 
 {
 'title': 'example glossary',
 'GlossDiv': 
 {
 'title': 'S',
 'GlossList': 
 {
 'GlossEntry': 
 {
 'ID': 'SGML',
 'ItemNumber': 2, 
 'SortAs': 'SGML',
 'GlossTerm': 'Standard Generalized Markup Language',
 'Acronym': 'SGML',
 'Abbrev': 'ISO 8879:1986',
 'GlossDef': 
 {
 'para': 'A meta-markup language, used to create markup languages such as DocBook.',
 'GlossSeeAlso': ['GML', 'XML']
 },
 'GlossSee': 'markup'
 }
 }
 }
 }
 }
 ";
 var d = new JsonDeserializer(json);
 d.GetString("glossary.title").Dump();
 d.GetString("glossary.GlossDiv.title").Dump(); 
 d.GetString("glossary.GlossDiv.GlossList.GlossEntry.ID").Dump(); 
 d.GetInt("glossary.GlossDiv.GlossList.GlossEntry.ItemNumber").Dump(); 
 d.GetObject("glossary.GlossDiv.GlossList.GlossEntry.GlossDef").Dump(); 
 d.GetObject("glossary.GlossDiv.GlossList.GlossEntry.GlossDef.GlossSeeAlso").Dump(); 
 d.GetObject("Some Path That Doesnt Exist.Or.Another").Dump(); 
}
// Define other methods and classes here
public class JsonDeserializer
{
 private IDictionary<string, object> jsonData { get; set; }
 public JsonDeserializer(string json)
 {
 var json_serializer = new JavaScriptSerializer();
 jsonData = (IDictionary<string, object>)json_serializer.DeserializeObject(json);
 }
 public string GetString(string path)
 {
 return (string) GetObject(path);
 }
 public int? GetInt(string path)
 {
 int? result = null;
 object o = GetObject(path);
 if (o == null)
 {
 return result;
 }
 if (o is string)
 {
 result = Int32.Parse((string)o);
 }
 else
 {
 result = (Int32) o;
 }
 return result;
 }
 public object GetObject(string path)
 {
 object result = null;
 var curr = jsonData;
 var paths = path.Split('.');
 var pathCount = paths.Count();
 try
 {
 for (int i = 0; i < pathCount; i++)
 {
 var key = paths[i];
 if (i == (pathCount - 1))
 {
 result = curr[key];
 }
 else
 {
 curr = (IDictionary<string, object>)curr[key];
 }
 }
 }
 catch
 {
 // Probably means an invalid path (ie object doesn't exist)
 }
 return result;
 }
}
answered Sep 16, 2011 at 14:55

Comments

15

As tripletdad99 said

var result = JsonConvert.DeserializeObject<T>(json);

but if you don't want to create an extra object you can make it with Dictionary instead

var result = JsonConvert.DeserializeObject<Dictionary<string, string>>(json_serializer);
Ognyan Dimitrov
6,2832 gold badges53 silver badges74 bronze badges
answered Oct 26, 2018 at 11:51

1 Comment

This is usefull, wheh you then pass parameters to Url.Action(action,controller,result)
11

add this ddl to reference to your project: System.Web.Extensions.dll

use this namespace: using System.Web.Script.Serialization;

public class IdName
{
 public int Id { get; set; }
 public string Name { get; set; }
}
 string jsonStringSingle = "{'Id': 1, 'Name':'Thulasi Ram.S'}".Replace("'", "\"");
 var entity = new JavaScriptSerializer().Deserialize<IdName>(jsonStringSingle);
 string jsonStringCollection = "[{'Id': 2, 'Name':'Thulasi Ram.S'},{'Id': 2, 'Name':'Raja Ram.S'},{'Id': 3, 'Name':'Ram.S'}]".Replace("'", "\"");
 var collection = new JavaScriptSerializer().Deserialize<IEnumerable<IdName>>(jsonStringCollection);
answered Jul 17, 2012 at 12:56

Comments

8

Copy your Json and paste at textbox on json2csharp and click on Generate button.

A cs class will be generated use that cs file as below

var generatedcsResponce = JsonConvert.DeserializeObject(yourJson);

Where RootObject is the name of the generated cs file;

Wictor Chaves
1,1591 gold badge15 silver badges25 bronze badges
answered Jan 17, 2019 at 10:19

Comments

8

Another fast and easy way to semi-automate these steps is to:

  1. take the JSON you want to parse and paste it here: https://app.quicktype.io/ . Change language to C# in the drop down.
  2. Update the name in the top left to your class name, it defaults to "Welcome".
  3. In visual studio go to Website -> Manage Packages and use NuGet to add Json.Net from Newtonsoft.
  4. app.quicktype.io generated serialize methods based on Newtonsoft. Alternatively, you can now use code like:

    WebClient client = new WebClient();

    string myJSON = client.DownloadString("https://URL_FOR_JSON.com/JSON_STUFF");

    var myClass = Newtonsoft.Json.JsonConvert.DeserializeObject(myJSON);

answered Nov 3, 2017 at 5:32

3 Comments

Link no longer valid
Thanks Myles J, I updated to a new site that seems to work fine.
app.quicktype.io is a good reference. here's another similar website - jsonformatter.org/json-to-csharp
3

Let's say :

var jsonString = "{ \"test\":\"some data\" }";

You can use the new System.Text.Json library as follows, which works after and including .Net Core 3.1:

...
var result = System.Text.Json.JsonSerializer.Deserialize<T>(jsonString);
Where T is your object type that matches your JSON string.

which if you don't want to define a 'type' you can use it like this

...
var result = System.Text.Json.JsonSerializer.Deserialize<dynamic>(jsonString);
answered Nov 25, 2023 at 8:22

4 Comments

using dymanic converts it to JsonElement, which is not usable. What you want is to use <JsonNode> and then access fields with result["test"]
You are right , you can also use dynamic like result.test .
Sadly you can't. That's what I'm saying. Try your code, result will be of type Json.JsonElement and can't access any of the fields. Deserialize<dynamic> is not creating a dynamic object with the json fields. You have to use <JsonNode> to get dynamic access to the fields. You could do (dynamic)JsonSerializer.Deserialize<ExpandoObject>() (might run into problems with nested fields) or use newtonsoft which supports dynamic with JsonConvert.DeserializeObject<dynamic>()
You are right, thanks for your attention.
1

Convert a JSON string into an object in C#. Using below test case.. its worked for me. Here "MenuInfo" is my C# class object.

JsonTextReader reader = null;
try
{
 WebClient webClient = new WebClient();
 JObject result = JObject.Parse(webClient.DownloadString("YOUR URL"));
 reader = new JsonTextReader(new System.IO.StringReader(result.ToString()));
 reader.SupportMultipleContent = true;
}
catch(Exception)
{}
JsonSerializer serializer = new JsonSerializer();
MenuInfo menuInfo = serializer.Deserialize<MenuInfo>(reader);
MNie
1,3672 gold badges17 silver badges35 bronze badges
answered Dec 20, 2016 at 8:19

1 Comment

Requires Newtonsoft.Json.dll / reference, agree?
0

First you have to include library like:

using System.Runtime.Serialization.Json;
DataContractJsonSerializer desc = new DataContractJsonSerializer(typeof(BlogSite));
string json = "{\"Description\":\"Share knowledge\",\"Name\":\"zahid\"}";
using (var ms = new MemoryStream(ASCIIEncoding.ASCII.GetBytes(json)))
{
 BlogSite b = (BlogSite)desc.ReadObject(ms);
 Console.WriteLine(b.Name);
 Console.WriteLine(b.Description);
}
0xdb
3,7071 gold badge23 silver badges39 bronze badges
answered Dec 10, 2017 at 14:58

Comments

0

Let's assume you have a class name Student it has following fields and it has a method which will take JSON as a input and return a string Student Object.We can use JavaScriptSerializer here Convert JSON String To C# Object.std is a JSON string here.

 public class Student
{
 public string FirstName {get;set:}
 public string LastName {get;set:}
 public int[] Grades {get;set:}
}
public static Student ConvertToStudent(string std)
{
 var serializer = new JavaScriptSerializer();
 Return serializer.Deserialize<Student>(std);
 }
answered Nov 21, 2020 at 3:15

Comments

0

Or, you can use the System.Text.Json library as follows:

using System.Text.Json;
...
var options = new JsonSerializerOptions()
 {
 PropertyNameCaseInsensitive = true
 });
var result = JsonSerializer.Deserialize<List<T>>(json, options);

Where T is your object type that matches your JSON string.

System.Text.Json is available in: .NET Core 2.0 and above .NET Framework 4.6.1 and above

answered Jun 13, 2022 at 6:02

Comments

0

For users using .Net Core 3.1 or newer

Or, you can use the new System.Text.Json library as follows, which works after and including .Net Core 3.1:

...
var result = System.Text.Json.JsonSerializer.Deserialize<T>(jsonString);

Where T is your object type that matches your JSON string.

answered Mar 15, 2023 at 18:38

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.