0

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?

h3n
  • 880
  • 1
  • 10
  • 26

2 Answers2

2

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();
Seth
  • 972
  • 1
  • 7
  • 18
  • Also, might I suggest using newtonsoft.json instead. It is the most popular json library. [https://www.newtonsoft.com/json](https://www.newtonsoft.com/json) – Seth Jun 27 '19 at 23:52
  • Thanks for the suggestion, but for now I will stick to System.Json. Converting the array to an IEnumerable is a nice way of doing it, thanks. I still wonder, how the heck did Microsoft intend their JsonArray.Contains() method to work? – h3n Jun 28 '19 at 00:16
1

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.

dezfowler
  • 1,238
  • 10
  • 20