Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# How to parse json data without key name?

Tags:

json

c#

.net

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.

like image 950
Matthew Avatar asked Feb 10 '23 08:02

Matthew


2 Answers

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();
like image 184
Jon Skeet Avatar answered Feb 13 '23 01:02

Jon Skeet


string jsonString = @"{""fields"":[{""type"":""none"",""options"":[""option1"",""option2"",""option3""]}]}";

var obj = JObject.Parse(jsonString);
var options = obj["fields"][0]["options"].ToList();
like image 40
Pawel Rosinski Avatar answered Feb 13 '23 01:02

Pawel Rosinski