devHead
devHead

Reputation: 822

Deserialize stringified JSON object

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.

Upvotes: 2

Views: 4048

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503140

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.

Upvotes: 6

Related Questions