h3n
h3n

Reputation: 898

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?

Upvotes: 1

Views: 1092

Answers (2)

dezfowler
dezfowler

Reputation: 1258

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.

Upvotes: 1

Seth
Seth

Reputation: 1072

I've never used System.Json before but it seems like it might be a type error (comparing an int with a JsonValue). you can convert the values to int before checking and that should work. Here is an example using linq.

bool bar = ((JsonArray)JsonValue.Parse("{\"foo\": [1,2,3]}")["foo"]).Select(a=>(int)a).Contains(2);
Console.WriteLine($"contains 2?: {bar}");
Console.ReadKey();

Upvotes: 2

Related Questions