Natali
Natali

Reputation: 55

Get only one variable from json response

I make a POST request and I get back json response with a lot of transactions in it like:

"Transactions": [
{
"ID": "1",
"Name" : "name",
"Code": "123aaa"
},
{
"ID": "2",
"Name" : "name1",
"Code": "12345bbb"
}
]

Is there any simple way to get one variable (for example first "Code" value)? Without entity classes etc? I've tried this

var content = new StringContent(request, Encoding.UTF8, "application/json");
            var response = await HttpClient.PostAsync(postURL, content);
            var text = await response.Content.ReadAsStringAsync();

var code = JObject.Parse(text).Children().First().Values<string>("Code").First();

But it didn't work:

System.InvalidOperationException : Cannot access child value on Newtonsoft.Json.Linq.JValue.

Upvotes: 0

Views: 794

Answers (1)

Guru Stron
Guru Stron

Reputation: 143023

Assuming that provided json is actually an object (i.e. string in question is wrapped in curly brackets) - you can use json path:

var code = JObject.Parse(text).SelectToken("$.Transactions[0].Code").ToString(); // results in "123aaa"

If you are keen on using LINQ to JSON you can do something like this:

var code = JObject.Parse(text)
    .Descendants()
    .OfType<JProperty>()
    .Where(p => p.Name == "Code")
    .Select(p => p.Value.ToString())
    .FirstOrDefault();

But the easiest I think would be to use indexers:

var code = JObject.Parse(text)["Transactions"][0]["Code"].ToString();

Upvotes: 2

Related Questions