4

I have json string like this:

{"fields":[{"type":"none","options":["option1","option2","option3"]}]}

I'm using JObject to parse json data. I can parse data that has name, like type, etc. But how can I parse data that doesn't have a name, like option1, option2 and option3? Here is my code:

JObject object = JObject.Parse(jsonString);
var type = object["fields"][0]["type"].ToString();

but problem is with options.

1
  • 1
    As an aside, it's helpful if you can post real, compilable code - you can't use object as an identifier. If you had posted a short but complete program demonstrating the problem, it would have been easier to help you. Commented Apr 27, 2015 at 11:09

2 Answers 2

7

The value of options is just an array of values - like fields is. But each value in there is just a string, rather than a further map of key/value pairs.

So you could use:

string firstOption = (string) jsonObject["fields"][0]["options"][0];

If you want the whole set of options as a List<string>, you can use:

var options = jsonObject["fields"][0]["options"]
    .Select(option => (string) option)
    .ToList();
Sign up to request clarification or add additional context in comments.

3 Comments

thank you for your reply. I tried that. I get null reference exception.
@Matthew: Well with the exact JSON you've given, the code I've provided works fine. So I suspect you've got a typo there, or your JSON doesn't actually look like that.
Thank you, your code was working fine. I deleted other part of code so I got exception at that line.
2
string jsonString = @"{""fields"":[{""type"":""none"",""options"":[""option1"",""option2"",""option3""]}]}";

var obj = JObject.Parse(jsonString);
var options = obj["fields"][0]["options"].ToList();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.