sd_dracula
sd_dracula

Reputation: 3896

C# Json to List

I have a json object as follows:

"dnsNames": {
      "type": "array",
      "defaultValue": [
        "something.else.com",
        "something.com",
        "else.com"
      ]
    }

I'd like to read that into a List<string> the same way I can read it into a string (i.e. without creating a class for it):

JObject jsonParameters = JObject.Parse(File.ReadAllText(filePath));
string test = jsonParameters["parameters"]["dnsNames"]["defaultValue"].ToString();

Just unsure if that's possible or what the syntax for it might be.

Upvotes: 0

Views: 63

Answers (1)

Kevin Smith
Kevin Smith

Reputation: 14436

Navigate the object structure as you see it dnsNames.defaultValue then convert that object to a given type (List<string> in our case):

var json =
  @"{""dnsNames"": {
  ""type"": ""array"",
  ""defaultValue"": [
    ""something.else.com"",
    ""something.com"",
    ""else.com""
  ]
}}";

var jObject = JObject.Parse(json);
var list = jObject["dnsNames"]["defaultValue"].ToObject<List<string>>();

// ?list
// Count = 3
// [0]: "something.else.com"
// [1]: "something.com"
// [2]: "else.com"

Upvotes: 4

Related Questions