Search code examples
c#.netobjectcontains

Check if JSON contains something C#


Basically I get the current item stock from Supreme in JSON. Then I deserialize it to object. I have been trying to check if the object contains the desired item, and get its id.


Solution

  • Based on the data coming back from that endpoint, you probably need to look a little deeper, which is easiest to do with JObject's SelectToken method.

        var shop_object = JsonConvert.DeserializeObject<JObject>(shop_json);
        Console.WriteLine(shop_object);
    
        try
        {
            if (shop_object.SelectTokens("$..name").Any(t => t.Value<string>() == DesiredItem))
            {
                Console.WriteLine("\n \n The desired item is in stock");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("error keyword");
        }
    

    Note that this uses an equality check on the string, so little details like the space at the end of "Reversible Bandana Fleece Jacket " can potentially throw you off.