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
Do you need to use JsonNode?
This loops through all properties:
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>
.If the values are of different types, you could create a custom JsonConverter and deserialize to a Dictionary<string, object>.
the simpliest way is to use linq
and to display
output
or to Dictionary