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
: 1494 At:- 5/25/2017 3:32:46 PM
JSON C# serialization deserialization






2 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





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