Search code examples
c#jsonjson.netjsonpath

How to query multiple fields from json string?


I have the following json string:

[
    {
        "id": 1,
        "type": "bird",
        "includeorexclude": "include"        
    },
    {
        "id": 2,
        "type": "animal",
        "includeorexclude": "include"       
    },
    {
        "id": 3,
        "type": "animal",
        "includeorexclude": "exclude"       
    }
]

And here is the code to select type from each json object:

var queries = JArray.Parse(json);
var queryTypes = queries.SelectTokens("$..type")
                        .Select(x => x.Value<string>())
                        .ToList();


foreach (var type in queryTypes)
{
    // var message = CreateMessage();
    // message.UserProperties.Add("Type", type);    
}

How do I get both type and includeorexclude from each json object?


Solution

  • you can use an anonymos type

        var jsonParsed = JArray.Parse(json);
    
        var queryTypes = jsonParsed.Select(x => new
        {
            type = (string)x["type"],
            includeorexclude = (string)x["includeorexclude"]
        }
        ).ToList();
    
        foreach (var type in queryTypes)
        {
            Console.WriteLine(type.type);
            Console.WriteLine(type.includeorexclude);
        }
    

    or create a class instead of an anonymous type