简体   繁体   中英

Deserialise JSON to Dictionary<string, ...> tree

In PHP and Python I can deserialise a JSON document to a dictionary structure. That's the default behaviour and there are not many other options anyway. In C#, hovever, all is typed and System.Text.Json methods want to know what type to deserialise into. Since I don't know the structure of the JSON document and just need to pass it on to something that can handle a dictionary, I need to convert it to that.

This doesn't work as expected:

var dict = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, object>>("{ \"a\": 1, \"b\": { \"c\": 3 } }");

At least what the VSCode debugger shows me, I have a dictionary with the keys "a" and "b" but the values are anything. I'd expect to see an int as value for "a" and another Dictionary as value for "b" with an int for the value "c".

How can this be achieved?

I'm looking for something like this:

// Does not exist:
var dict = System.Text.Json.JsonSerializer.DeserializeToDictionary("{ \"a\": 1, \"b\": { \"c\": 3 } }");

I'm trying to convert a class that I've written in Python because I hit other roadblocks in Python. I'm more experienced in C# so I'd like to solve the problem there, but JSON for dynamic data isn't a strength of C#. Seems I have to write some classes of my application in Python and others in C# to get it done.

Newtonsoft.Json fits much better for the complicated cases. You can try this code

   using Newtonsoft.Json;

    var jsonParsed = JObject.Parse(json);
    var dict = new Dictionary<string, object>();
    
    AddDictionaries(dict,jsonParsed);

public void AddDictionaries(Dictionary<string, object> dict, JObject jsonObj)
{
    foreach (var prop in jsonObj)
    {
        if (prop.Value.Type != JTokenType.Object)
            dict.Add(prop.Key, prop.Value);
        else
        {
            var nestedDict = new Dictionary<string, object>();
            AddDictionaries(nestedDict, (JObject)prop.Value);
            dict.Add(prop.Key, nestedDict);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM