thatOneGuy
thatOneGuy

Reputation: 10642

Check if string appears in list of JValues

I have some JSON which I inspect and parse into a JArray. The JSON is similar to this :

"required" : [ "1", "2" ]

Now when it parses, the outcome is an array of JValues. I want to check if my string appears in this list. So, to do this, I do :

JArray requiredArray = JArray.Parse(myJson["required].ToString());

bool exists = requiredArray.Contains("1");

This comes back as false, and I think its due to it comparing a JValue with a string. I try convert the string to a JValue like so :

JValue itemValue = JValue.Parse("1");

It doesn't like that, says cannot convert JToken to JValue.

All I need to know is, does my JArray contain this string value.

Upvotes: 4

Views: 6629

Answers (3)

Truning
Truning

Reputation: 107

.Contains() does not work in this case, because as mentioned in JArray.Contains issue, JArrays compare references and not the actual value. (This is also to answer Patrick's comment in his answer.)

You could do somethin like this:

public static bool ContainsString(this JArray jArray, string s)
{
    return jArray.Any(x => x.ToString().Equals(s));
}

And use it like so:

if (requiredArray.ContainsString("1")) {
 //...
}

Upvotes: 1

ccaskey
ccaskey

Reputation: 202

You could convert the JArray to a string array, that way you'd be able to do .Contains() like you wanted to originally:

string[] strings = requiredArray.ToObject<string[]>();

bool exists = strings.Contains("1");

Upvotes: 4

Patrick Hofman
Patrick Hofman

Reputation: 157136

You can use Any:

bool exists = requiredArray.Any(t => t.Value<string>() == "1");

Upvotes: 15

Related Questions