skip to Main Content

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?

2

Answers


  1. 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>.

    Login or Signup to reply.
  2. 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: "
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search