0

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.

1
  • 2
    data is not an array, and the first foo property of the object data will be overwritten by the second foo property. Maybe you meant to make data an array? Commented Jun 25, 2014 at 16:04

1 Answer 1

1

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");
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you but it seems valid when i check on this url jsonformatter.curiousconcept.com
@Kerberos there is a difference between syntactically correct and correct based on your intent.
@Kerberos: As iamkrillin says, your JSON is valid, you're just not accessing it correctly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.