-4

I send a request to an API and I get this JSON back:

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

I can get the value of the name item easily:

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

But I also need the values of the Username and Password items. How can I do that?

John
  • 6,404
  • 14
  • 54
  • 106

1 Answers1

1

You can create a class for your json by simply pasting your JSON object in the menu VS Edit/Special paste

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; }
}

then

Rootobject testData = JsonConvert.DeserializeObject<Rootobject>(json);
Antoine V
  • 6,998
  • 2
  • 11
  • 34
  • 4
    Instead of posting this, it would have been much better to point OP to the "Paste JSON as classes" option that you used here. Or point them at one of the the thousands of other "how do I parse JSON" questions. – DavidG Nov 07 '18 at 10:18
  • Ah great! And how would getting that value than be? `testData.testvalues.name`? – John Nov 07 '18 at 10:18
  • 1
    @John Almost, `testData.testvalues[index].name;` becuse is `testvalues` if of type `List` – styx Nov 07 '18 at 10:20
  • 2
    @styx No, it is an array. – Patrick Hofman Nov 07 '18 at 10:20