[英]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 eg 在myJSON中,除了结尾处的数字外,将有数量不等的具有相同名称的项目,例如
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. 有时可能有3个(如上所述),有时可能有12个,其他时候只有1个或任何其他数字。
How can I add them all to strings when I don't know how many there will be? 不知道会有多少个字符串时,如何将它们全部添加到字符串中?
TIA TIA
You might have better luck not using dynamic
. 如果不使用dynamic
可能会更好。 With a JObject
you can index into it with a string: 使用JObject
您可以使用字符串将其索引到其中:
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
. 您可以使用myJSON.Count
获得项目myJSON.Count
。
This is all assuming your structure is flat and you don't need to drill into nested objects. 所有这些都假设您的结构是平坦的,并且不需要钻取嵌套对象。
You could deserilize the data into a dictionary and then iterate through the keys. 您可以将数据反序列化为字典,然后遍历键。 eg 例如
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. 尽管在上面的示例中我假设该值是一个字符串,但是它可以是任何对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.