Simon
Simon

Reputation: 47

Reference varying names in JSON object C#

I have the following:

dynamic myJSON = JsonConvert.DeserializeObject(data);

Within myJSON there will be a varying number of items that have the same name apart from a number at the end e.g.

string v1 = myJSON.variable1;
string v2 = myJSON.variable2;
string v3 = myJSON.variable3;

Sometimes there could be 3 (as above), sometimes there could be 12, at other times, only 1, or any other number.

How can I add them all to strings when I don't know how many there will be?

TIA

Upvotes: 0

Views: 200

Answers (2)

Paul Houlston
Paul Houlston

Reputation: 256

You could deserilize the data into a dictionary and then iterate through the keys. e.g.

var data = @"{ ""variable1"":""var1"", ""variable2"":""var2"", ""variable3"":""var3"", ""variable4"":""var4"" }";
var deserializedDictionary  = JsonConvert.DeserializeObject<Dictionary<string,string>>(data);
foreach(var item in deserializedDictionary)
{
    Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");
}

Although I have assumed the value is a string in the example above, it could be any object.

Upvotes: 0

Crowcoder
Crowcoder

Reputation: 11514

You might have better luck not using dynamic. With a JObject you can index into it with a string:

string variableName = "something";
var myJSON = JObject.Parse(data);
string v1 = myJSON[variableName + "1"];
string v2 = myJSON[variableName + "2"];
//...etc.

Update

You can get the number of items with myJSON.Count.

This is all assuming your structure is flat and you don't need to drill into nested objects.

Upvotes: 2

Related Questions