Json结构问题

时间:2014-03-06 11:25:29

标签: asp.net json.net

第三方API以以下格式返回JSON

{
"group1": {
    "Colour": "Blue",
    "Name": "Dave"
},
"group2": {
    "Colour": "Red",
    "Name": "Karen"
},
"group3": {
    "Colour": "Green",
    "Name": "Ryan"
 }
}

在尝试使用JSON.NET反序列化JSON时,我发现外部'groupX'标识符有问题。

有谁知道以这种格式解析JSON最好?

3 个答案:

答案 0 :(得分:0)

{
    "employees": [
        { "first-name":"John" , "last-name":"Doe" },
        { "first-name":"Anna" , "last-name":"Smith" },
        { "first-name":"Peter" , "last-name":"Jones" }
    ]
}

答案 1 :(得分:0)

你的JSON是正确的。 如果想要检查而不是使用以下网址JSONlint

答案 2 :(得分:0)

像这样定义一个类Group

class Group
{
    public string Colour { get; set; }
    public string Name { get; set; }
}

然后你可以像这样反序列化:

var dict = JsonConvert.DeserializeObject<Dictionary<string, Group>>(json);

这是一个快速演示:

string json = @"
{
""group1"": {
    ""Colour"": ""Blue"",
    ""Name"": ""Dave""
},
""group2"": {
    ""Colour"": ""Red"",
    ""Name"": ""Karen""
},
""group3"": {
    ""Colour"": ""Green"",
    ""Name"": ""Ryan""
 }
}";

var dict = JsonConvert.DeserializeObject<Dictionary<string, Group>>(json);
foreach (var kvp in dict)
{
    Console.WriteLine(kvp.Key);
    Group group = kvp.Value;
    Console.WriteLine("  Colour: " + group.Colour);
    Console.WriteLine("  Name: " + group.Name);
}

输出:

group1
  Colour: Blue
  Name: Dave
group2
  Colour: Red
  Name: Karen
group3
  Colour: Green
  Name: Ryan