Home > Software engineering >  How to query multiple fields from json string?
How to query multiple fields from json string?

Time:07-28

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?

CodePudding user response:

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

CodePudding user response:

You can just create a class that has properties type and includeorexclude. Then you create new objects with that class and assign your data with your query. After that a generic list can contain all you need.

  • Related