2

I've read a few posts on how to do this, but everything that i've seen the JSON object has specific property names to query, where i do not.

Here is my JSON string:

{
  "424406": true,
  "425171": true,
  "411961": true
}

I want to loop through the array and read the string and bool field in separately (the JSON string is stored in a hidden variable, then accessed in my asp.net code behind):

dynamic dynObj = JsonConvert.DeserializeObject(partDetailsSelectedItems.Value);

foreach (dynamic x in dynObj)
{
   string Id = ????
   bool boolValue = ???
}

how do i get each of the 2 objects in "x" without specifying the name?

Ideally, i'd like to convert this stringified JSON into a generic list

List<string,bool>

but i need to understand how to handle my above scenario.

devHead
  • 794
  • 1
  • 15
  • 38

1 Answers1

6

If you use LINQ to JSON it's simple, because JObject allows you to iterate over all the key/value pairs - it implements IEnumerable<KeyValuePair<string, JToken>>:

using System;
using System.IO;
using Newtonsoft.Json.Linq;

class Test
{
    public static void Main(string[] args)
    {
        string text = File.ReadAllText("test.json");
        var json = JObject.Parse(text);

        foreach (var pair in json)
        {
            string id = pair.Key;
            bool value = (bool) pair.Value;
            Console.WriteLine("id: {0}; value: {1}", id, value);
        }
    }
}

The cast for the value is calling the explicit conversion from JToken to bool. No need for dynamic here at all.

Alternatively, as noted in comments, you can just deserialize to a Dictionary<string, bool>:

using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;

class Test
{
    public static void Main(string[] args)
    {
        string text = File.ReadAllText("test.json");
        var dictionary = JsonConvert.DeserializeObject<Dictionary<string, bool>>(text);

        foreach (var pair in dictionary)
        {
            string id = pair.Key;
            bool value = pair.Value;
            Console.WriteLine("id: {0}; value: {1}", id, value);
        }
    }
}

I usually end up using LINQ to JSON myself, but either approach works and which is better depends on your context.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • @John Skeet, thank you. I did not know i could easily deserialize to a dictionary – devHead Aug 14 '14 at 12:42
  • 2
    The second part to this answer was really what my original answer was (poorly) trying to get at....deserialize as a dictionary rather than `dynamic`. There was no point in re-editing it to repeat the same code. – James Aug 14 '14 at 12:44
  • @James your code will get an *InvalidCastException* – L.B Aug 14 '14 at 12:57
  • @L.B not if it was an `ExpandoObject`, that was the issue with my answer to begin with, I was just assuming it was. – James Aug 14 '14 at 13:00