Search code examples
c#system.json

How to properly use System.Json.JsonArray.Contains()


I want to use the System.Json.JsonArray.Contains() to see if my Array contains a specific value. Below is a minimum example. I expect both varibales bar and baz to be true, but they're both false. nuget package System.Json v4.5 was used.

    using System;
    using System.Json;

    public class Program
    {
        public static void Main()
        {
            bool bar = ((JsonArray)JsonValue.Parse("{\"foo\": [1,2,3]}")["foo"]).Contains(2);
            bool baz = ((JsonArray)JsonValue.Parse("{\"foo\": [1,2,3]}")["foo"]).Contains(new JsonPrimitive(2));
            Console.WriteLine($"contains 2?: {bar} {baz}");
            Console.ReadKey();
        }
    }

Using System.Json, how do I check, if an array contains a numeric value and why does the above example return false?


Solution

  • JsonArray.Contains() performs a List.Contains internally here so in this case it's actually going to perform a reference comparison meaning you'd need to pass it the actual instance of the JsonPrimitive already in the array that you were looking for. Same goes for all the other methods of JsonArray that take a JsonValue. Not very useful for your use case.

    The API in general seems a bit clunky and not well thought out and Stephen Toub actually refers to it as the "legacy System.Json library" in this commit message from January so I would guess this library was deprecated by Microsoft in favour of JSON.NET and I'd agree with Seth that you'd be better off using that instead.

    If you still want to stick with it, Seth's solution using the Select() is probably the way to go.