Kurkula
Kurkula

Reputation: 6762

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 first item value from 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;

Upvotes: 0

Views: 2699

Answers (3)

Zein Makki
Zein Makki

Reputation: 30042

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.

Upvotes: 1

Justin CI
Justin CI

Reputation: 2741

You can deserialize the json with

     public class Details
        {
            public string name { get; set; }
            public string city { get; set; }
        }

  var res = JsonConvert.DeserializeObject<Details[]>(json);
  var name = res[0].name;

Upvotes: 1

Slava Utesinov
Slava Utesinov

Reputation: 13488

Try this:

var NameInFirstItem = jsonObject[0]["name"];

Upvotes: 1

Related Questions