AlbatrossCafe
AlbatrossCafe

Reputation: 1842

How to get all lines of JSON without knowing schema with JsonNode?

Let's say I am expecting a simple JSON response from an API like so:

{
  "message": "Source: ",
  "incomingUrl": "https://10.1.1/api/echo",
  "incomingHeadersCount": 21,
  "apiVersion": "1.0"
}

I can use JsonNode to parse it and output the lines. This requires me to access it by specifying the key:

var parsedJson = JsonNode.Parse(apiResponse.Result);
Console.WriteLine(parsedJson["message"]);

I'd prefer to do something like this where I don't have to know any of the keys:

foreach (var item in parsedJson)
{
    Console.WriteLine(item);
}

This should return, "Source: ", "https://10.1.1/api/echo", "21", "1.0". Is this possible with JsonNode?

Upvotes: 0

Views: 719

Answers (2)

Serge
Serge

Reputation: 43959

the simpliest way is to use linq

List<JsonValue> data = JsonNode.Parse(apiResponse.Result).AsObject()
                               .AsEnumerable().Select(d => d.Value.AsValue())
                               .ToList();

and to display

Console.WriteLine(string.Join(", ", data));

output

Source: , https://10.1.1/api/echo, 21, 1.0

or to Dictionary

Dictionary<string,string> dict = JsonNode.Parse(apiResponse.Result).AsObject()
                                         .ToDictionary(d => d.Key, 
                                                       d => d.Value.ToString());
                               
 Console.WriteLine(dict["message"]); // "source: "

Upvotes: -1

JOSEFtw
JOSEFtw

Reputation: 10091

Do you need to use JsonNode?

This loops through all properties:

var data = JsonNode.Parse(apiResponse.Result).AsObject();
foreach(var item in data)
{
    var key = item.Key;
    var value = item.Value;
    Console.WriteLine(value);

}

One drawback with this approach is that you'll need to know what type the value is, since you'll need to call .GetValue<T>() on the value. Assuming it's always a string, just call .GetValue<string>(). If you just want to print the value you are fine though.

You could also deserialize directly to a Dictionary<string, string>.

var items = JsonSerializer.Deserialize<Dictionary<string, string>(apiResponse.Result);

foreach(var item in items)
{
    Console.WriteLine(item.Value);
}

If the values are of different types, you could create a custom JsonConverter and deserialize to a Dictionary<string, object>.

Upvotes: 1

Related Questions