0

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

2
  • 1
    you could use a List; well need more info, though, like example JSON, Mapping class, ... Commented Aug 23, 2018 at 14:14
  • Do you have control or at least some say in the structure of that json? Commented Aug 23, 2018 at 14:16

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Good first step. Still he has to know the count of the properties at compiletime. Edit: I was pointing towards string v1=... could be replaced by a List ;)
Thanks. I've been able to sort it with this.
0

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.

Comments

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.