Chandana Chandana - 6 months ago 15
JSON Question

Reading first item in serialized json

I am trying to get name from first item in deserialized json object. When I debugged code, i found that jsonObject is converted to dictionary. How can I get 1st item value in jsonObject.

var myJson= [
{name:'abc',city:'dallas'},
{name:'def',city:'redmond'},
{name:'ghi',city:'bellevue'},
]

JavaScriptSerializer jss = new JavaScriptSerializer();
var jsonObject = jss.Deserialize<dynamic>(myJson);

NameInFirstItem = jsonObject[0].name;

Answer

Create a class to hold your resulting object:

public class MyJsonResult
{
    public string name { set; get; }
    public string result { set; get; }
}

static void Main(string[] args)
{
    string myJson = "[{ name: 'abc',city: 'dallas'},{ name: 'def',city: 'redmond'},{ name: 'ghi',city: 'bellevue'}]";

    JavaScriptSerializer jss = new JavaScriptSerializer();
    List<MyJsonResult> jsonResultList = jss.Deserialize<List<MyJsonResult>>(myJson);

    var NameInFirstItem = jsonResultList.FirstOrDefault().name;
}

Or if you insist on using dynamic:

static void Main(string[] args)
{
    string myJson = "[{ name: 'abc',city: 'dallas'},{ name: 'def',city: 'redmond'},{ name: 'ghi',city: 'bellevue'}]";

    JavaScriptSerializer jss = new JavaScriptSerializer();
    var jsonResultList = jss.Deserialize<List<dynamic>>(myJson);

    // get first value by key from the dictionary
    var NameInFirstItem = jsonResultList.FirstOrDefault()["name"];
}

I prefer the first method. If you add a third property to your json, you might get confused with type of the generated object, which is probably a list of key-value pairs for each object in your list.

Comments