Behzad Razzaqi
Behzad Razzaqi

Reputation: 71

Access json object value

I have a this code in asp.net ashx file:

jsonString="{'id':'54','name':'reza'}";
JavaScriptSerializer j = new JavaScriptSerializer();
var a = j.Deserialize(jsonString, typeof(object));

and get Json string and convert to 'a' object,How can i get value of a ? for example i need get id field value into [id,54] ?

Upvotes: 1

Views: 950

Answers (1)

haim770
haim770

Reputation: 49095

Since you don't specify a strongly-typed target type for the deserialization (other than object), JavaScriptSerializer will return a Dictionary<string, object> and you'll have to access it as follows:

string jsonString = "{'id':'54','name':'reza'}";
JavaScriptSerializer j = new JavaScriptSerializer();
dynamic data = j.Deserialize(jsonString, typeof(object));
string id = data["id"]; // equals 54

Yet, you better define your own custom type to access the deserialized data. Something like:

public class Person
{
    public string id { get; set; }
    public string name { get; set; }
}

string jsonString = "{'id':'54','name':'reza'}";
JavaScriptSerializer j = new JavaScriptSerializer();
Person person = j.Deserialize<Person>(jsonString);
string id = person.id; // equals 54

Upvotes: 1

Related Questions