Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize JSON string to c# object

My Application is in Asp.Net MVC3 coded in C#. This is what my requirement is. I want an object which is in the following format.This object should be achieved when I deserialize the Json string.

var obj1 = new { arg1=1,arg2=2 }; 

enter image description here

After using the below code:

string str = "{\"Arg1\":\"Arg1Value\",\"Arg2\":\"Arg2Value\"}"; JavaScriptSerializer serializer1 = new JavaScriptSerializer(); object obje = serializer1.Deserialize<object>(str); 

The object what i get i.e obje does not acts as obj1

enter image description here

Here, in this example my JSON string is static, but actually JSON string is going to be dynamically generated runtime, so i won't be able get Arg1 and Arg2 all the time.

like image 971
Shahbaz Chishty Avatar asked Apr 27 '12 12:04

Shahbaz Chishty


People also ask

How do I deserialize a JSON string?

A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.

What is serialize and deserialize in JSON?

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).


1 Answers

I think the JavaScriptSerializer does not create a dynamic object.

So you should define the class first:

class MyObj {     public int arg1 {get;set;}     public int arg2 {get;set;} } 

And deserialize that instead of object:

serializer.Deserialize<MyObj>(str); 

Not testet, please try.

like image 144
Marc Avatar answered Oct 16 '22 22:10

Marc