2

I am looking to use JSON.net to deserialize a JSON structure into a Dictionary. The trick is that the JSON document is a hierarchy of nested objects but I'd like to only look at the top-level property+value pairs.

Eg.

{
    "prop1": 142,
    "prop2": "Some description",
    "object_prop": {
        "abc": 2,
        "def": {
            "foo": "hello",
            "bar": 4
        }
    }
}

Based on the above example, I'd like to have my deserialized dictionary have 3 items in it: "prop1", "prop2", and "object_prop". "object_prop" should just be a string (which I will deserialize to an object at some later point in time.

Note: I'm looking to do this because I want to create a re-usable library that just knows about top-level key/value pairs and where clients consuming the library can define the type of the values at a later point in time. (ie. I don't want my re-usable library bound to the object types ... namely "object_prop").

1 Answer 1

4

How about something like this?

class Program
{
    static void Main(string[] args)
    {
        string json = @"
        {
            ""prop1"": 142,
            ""prop2"": ""Some description"",
            ""object_prop"": {
                ""abc"": 2,
                ""def"": {
                    ""foo"": ""hello"",
                    ""bar"": 4
                }
            },
            ""prop3"": 3.14
        }";

        Dictionary<string, string> dict = new Dictionary<string, string>();
        JObject jo = JObject.Parse(json);

        foreach (JProperty prop in jo.Properties())
        {
            if (prop.Value.Type == JTokenType.Array || 
                prop.Value.Type == JTokenType.Object)
            {
                // JSON string for complex object
                dict.Add(prop.Name, prop.Value.ToString(Formatting.None));  
            }
            else
            {
                // primitive value converted to string
                object value = ((JValue)prop.Value).Value;  
                dict.Add(prop.Name, value != null ? value.ToString() : null);
            }
        }

        foreach (KeyValuePair<string, string> kvp in dict)
        {
            Console.WriteLine(kvp.Key + " = " + kvp.Value);
        }
    }
}

Output:

prop1 = 142
prop2 = Some description
object_prop = {"abc":2,"def":{"foo":"hello","bar":4}}
prop3 = 3.14
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! I was heading towards a custom JsonConverter and it seemed overly complex. Thank-you! :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.