反序列化多个 JSON 变量时遇到问题 [英] Having trouble deserializing multiple JSON variable
问题描述
我编写了以下代码,它确实反序列化并解析了单个 JSON 变量,但是,它不适用于多个
I wrote the following code, it does deserialize and parse a single JSON variable, however, it won't work with multiple
API 检索到的 JSON 有类似下面的变量,但是,第一个分支有一个总是变化的数字,比如 value_abc_######,其中 ###### 是一个总是不同的数字,所以我不知道我得到了什么输出.
The JSON retrieved by API has variables similar to the following, however, the first branch has a number that always changes, like value_abc_######, where ###### is a always different number, so I have no idea on what output I get for this one.
这是我通过 API 调用返回的 JSON 结构:
This is the JSON structure I get returned by the API call:
{
"value_abc_154649": {
"Name": "",
"Address": "",
"Phone": "",
},
"value_abc_616447": {
"Name": "",
"Address": "",
"Phone": "",
},
"value_abc_912374": {
"Name": "",
"Address": "",
"Phone": ""
}
}
虽然这是我写的代码,但如果 JSON 只有 1 个分支结果,它可以正常工作,但如果有多个则不会
While this is the code I wrote, it works fine if the JSON has only 1 branch result, but with multiples it won't
class getVariables
{
public string Name { get; set; }
}
class fetch
{
var client = new System.Net.WebClient();
string json = client.DownloadString(API_URL);
var result = JsonConvert.DeserializeObject<getVariables>(json);
Console.Write("\nName: " + result.Name); //this just print an empty value
/*I also tried this structure but the for loop doesn't work
for (result)
{
Console.Write("\nName: " + result.Name);
}*/
}
推荐答案
你的类不代表你的 json 结构.尝试反序列化为 Dictionary
:
You class does not represent your json structure. Try deserializing to Dictionary<string, getVariables>
:
var json = @"{
""value_abc_154649"": {
""Name"": """",
""Address"": """",
""Phone"": """",
},
""value_abc_616447"": {
""Name"": """",
""Address"": """",
""Phone"": """",
},
""value_abc_912374"": {
""Name"": """",
""Address"": """",
""Phone"": """"
}
}";
var result = JsonConvert.DeserializeObject<Dictionary<string, getVariables>>(json);
// foreach(var r in result.Values)
// {
// Console.Write("\nName: " + r.Name);
//}
// or to print with keys:
foreach(var kvp in result)
{
Console.WriteLine($"Key: {kvp.Key}, Name: {kvp.Value.Name}");
}
这篇关于反序列化多个 JSON 变量时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!