获取嵌套的JSON值

时间:2018-11-07 10:13:49

标签: c# json

我向API发送请求,并获得了JSON:

{{
  "id": 1,
  "name": "LoginTest",
  "status": "ready",
  "testvalues_count": 2,
  "testvalues": [
    {
      "id": 1,
      "name": "Username",
      "value": "Test"
    },
    {
      "id": 2,
      "name": "Password",
      "value": "password1"
    }
  ]
}}

我可以轻松获得name项的值:

var api = new DataApi();
var json = api.GetTestData("LoginTest");
dynamic testData = JsonConvert.DeserializeObject<dynamic>(json);
var name = testData.name;

但是我还需要UsernamePassword项目的值。我该怎么办?

1 个答案:

答案 0 :(得分:1)

您只需在VS Edit / Special paste菜单中粘贴JSON对象即可为json创建一个类

public class Rootobject
{
    public int id { get; set; }
    public string name { get; set; }
    public string status { get; set; }
    public int testvalues_count { get; set; }
    public Testvalue[] testvalues { get; set; }
}

public class Testvalue
{
    public int id { get; set; }
    public string name { get; set; }
    public string value { get; set; }
}

然后

Rootobject testData = JsonConvert.DeserializeObject<Rootobject>(json);