Kerberos
Kerberos

Reputation: 1266

Parsing JSON using LINQ

My json data are as below.

{
   "data":{
      "foo":{
         "sfoo":"1",
         "active":1
      },
      "foo":{
         "sfoo":"2",
         "active":0
      },
      "v":"v1"
   }
}

I try to get the value from json with this code:

JObject _JObject = JObject.Parse(_JsonString);

var _JItems = _JObject.SelectToken("data[0].foo")
            .Select(s => new
            {
                _Sfoo = (string)s.SelectToken("sfoo"),
                _WhereClause = (string)s.SelectToken("active")
            })
    .Where(w => w._WhereClause == "1");

foreach (var _JItem in _JItems)
{
    MessageBox.Show(_JItem._Sfoo.ToString());
}

I am getting an error such as "Additional information: Value cannot be null."

Thank you in advance.

Upvotes: 0

Views: 77

Answers (1)

Andrew Whitaker
Andrew Whitaker

Reputation: 126052

As I commented, data is an object ({}) and not an array ([]). You're seeing an error because the object data has no property 0 defined.

It seems like you'd want your JSON to look something like this instead:

{
   "data":{
      "foo":[
         {
            "sfoo":"1",
            "active":1
         },
         {
            "sfoo":"2",
            "active":0
         }
      ],
      "v":"v1"
   }
}

Then your parsing code would look like this:

var _JItems = _JObject.SelectToken("data.foo")
        .Select(s => new
        {
            _Sfoo = (string)s.SelectToken("sfoo"),
            _WhereClause = (string)s.SelectToken("active")

        })
        .Where(w => w._WhereClause == "1");

Upvotes: 1

Related Questions