C# how to query dynamic json?

Viewed 72

If retrieve a JSON string for which the full schema is not known :

{
    ... other stuff
    "data": [
        {
            "open": 110.05,
            "high": 112.0,
            "low": 110.0,
            "close": 111.78,
            "volume": 21745034.0,
            "symbol": "GOOG",
            "exchange": "XNAS",
            "date": "2022-09-09T00:00:00+0000",
            ... more fields
        },
        ... more data

Then deserialize into dynamic :

var result = JsonConvert.DeserializeObject<dynamic>(response);

How to query for specific symbols ?

This doesn't work :

var match = result["data"].Where(e => e.Value["symbol"].ToString() == "GOOG").FirstOrDefault();

Gives error :

Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type.

1 Answers

if you are using System.Text.Json you can use JsonNode as Follows :

using System.Linq;
using System.Text.Json.Nodes;



var jsonObject = JsonNode.Parse(response)!.AsObject();

var match = jsonObject["data"]?.AsArray().FirstOrDefault(e => e["symbol"]?.ToString() == "GOOG");

//access properties
string open = match?["open"]?.ToString();

with Newtonsoft you can use JObject as Follows :

using System.Linq;
using Newtonsoft.Json.Linq;


var jsonObject = JObject.Parse(response);

var match = jsonObject["data"].FirstOrDefault(e => e["symbol"]?.ToString() == "GOOG");

//access properties
string open = match?["open"]?.ToString();
Related