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?
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
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.
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.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly