0

I'm deserialising JSON using JSON.Net along the same lines as the accepted solution to this question: Deserialize json object into dynamic object using Json.net. Essentially:

dynamic d = JObject.Parse("{number:1000, str:'string', array: [1,2,3,4,5,6]}");

Console.WriteLine(d.number);
Console.WriteLine(d.str);
Console.WriteLine(d.array.Count);

Difference being my array has strings rather than numbers. The above methods work fine. However, what I want to do is test if the array contains a particular value. If it was a typed array of strings I could use myArray.IndexOf("ValueToFind") and if it returns a value > -1 then it's in there. However, this isn't working and I think it's because it's actually an array of JValues rather than strings.

I can iterate through the array, cast each one to a string and then test (i.e. a foreach loop with an if statement inside) but I was hoping for a more succinct single line test. Can anyone advise if there is a simpler way to do the test?

Thanks

Community
  • 1
  • 1
Kate
  • 1,556
  • 1
  • 16
  • 33
  • I'm too lazy to try this but could you not use the extension method Any() such as if ( d.Any(p => p.ToString() == "Whatever") ) { //etc.. } – Lukos Sep 02 '14 at 15:10
  • Thanks, but unfortunately I get the message: "Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type" – Kate Sep 02 '14 at 15:16

2 Answers2

1

JSON.NET can seamlessly convert JArray to List<string>, so you can use

Console.WriteLine(d.array.ToObject<List<string>>().IndexOf("1"));

This works even with JSON integer array.

tia
  • 9,518
  • 1
  • 30
  • 44
1

I got a slightly messier answer by first converting your dynamic array to a known type:

IEnumerable<JToken> d2 = d.array;

Then you can use Any as an extension method.

if (d2.Any(p => p.ToString() == "1")) //etc.
Lukos
  • 1,826
  • 1
  • 15
  • 29