简体   繁体   中英

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] ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM