How to convert JSON String into C# class object


I am trying to convert JSON object into C# class object, 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?


Asked by:- jaya
1
: 5686 At:- 5/25/2017 3:32:46 PM
JSON C# serialization deserialization







3 Answers
profileImage Answered by:- vikas_jk

Hello thanks for asking question

It looks like you could create a Class that represents the object that you're converting to.

It would be helpful when you are dealing with larger JSON inputs also, so always try to create a class first.

Your class can be

public class Test {

      public string test {get;set;}
  }

After that, you can simply convert it by using this code

 JavaScriptSerializer oJS = new JavaScriptSerializer();

//here response.Content=   "{ \"test\":\"some data\" }"           
var obj= oJS.Deserialize<test>(response.Content);

i hope this help's

2
At:- 5/25/2017 4:21:41 PM
Good it work's 0
By : jaya - at :- 5/25/2017 4:25:42 PM
you can take a look on this https://qawithexperts.com/article/web-api/quick-tip-to-convert-json-into-class-object/26 ,also if you need further help 0
By : vikas_jk - at :- 5/25/2017 4:38:23 PM


profileImage Answered by:- pika

Although this is already marked as answer, if you just need to convert JSON string into C# class object than using Visual Studio  "Edit"->"Paste as Special"->"Paste JSON as class" will work for you.

Take a look at this article https://qawithexperts.com/article/web-api/quick-tip-to-convert-json-into-class-object/26 

OR

Use the answer of this question convert JSON string into C# class 

https://qawithexperts.com/questions/239/how-to-convert-dynamic-json-string-into-c-class

Hope this helps.

1
At:- 3/23/2018 10:38:42 AM Updated at:- 3/23/2018 10:39:16 AM


profileImage Answered by:- bhanu

To create a class of a JSON string, copy the string.

In Visual Studio, click Edit -> Paste special -> Paste Json as classes.

If you are missing this feature, then probably, your Visual Studio needs to install  "Web Development Tools plus .NET Core 2.1" component.

This is added when you install the ASP.NET and web development workload, but installing only the Web Development Tools plus .NET Core 2.1 component should be enough.

OR

Use the free jsonclassgenerator.exe

OR

Use an online tool like https://www.minify-beautify.com/json-to-csharp-class-online which also explains how they are converting JSON into C# Class.

1
At:- 1/20/2022 9:00:47 AM
Thanks your online json to C# class converter is helpful. 0
By : jaya - at :- 6/13/2022 7:43:34 AM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use