Json.NET: Deserializing nested dictionaries

前端 未结 3 488
野的像风
野的像风 2020-12-01 02:49

When deserializing an object to a Dictionary (JsonConvert.DeserializeObject>(json)) nested objects are deser

相关标签:
3条回答
  • 2020-12-01 03:23

    I found a way to convert all nested objects to Dictionary<string,object> by providing a CustomCreationConverter implementation:

    class MyConverter : CustomCreationConverter<IDictionary<string, object>>
    {
        public override IDictionary<string, object> Create(Type objectType)
        {
            return new Dictionary<string, object>();
        }
    
        public override bool CanConvert(Type objectType)
        {
            // in addition to handling IDictionary<string, object>
            // we want to handle the deserialization of dict value
            // which is of type object
            return objectType == typeof(object) || base.CanConvert(objectType);
        }
    
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.StartObject
                || reader.TokenType == JsonToken.Null)
                return base.ReadJson(reader, objectType, existingValue, serializer);
    
            // if the next token is not an object
            // then fall back on standard deserializer (strings, numbers etc.)
            return serializer.Deserialize(reader);
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            var json = File.ReadAllText(@"c:\test.json");
            var obj = JsonConvert.DeserializeObject<IDictionary<string, object>>(
                json, new JsonConverter[] {new MyConverter()});
        }
    }
    

    Documentation: CustomCreationConverter with Json.NET

    0 讨论(0)
  • 2020-12-01 03:25

    I had a very similar but slightly more complex need when I ran across this Q. At first I thought maybe I could adapt the accepted answer, but that seemed a bit complicated and I ended up taking a different approach. I was attempting to put a modern JSON layer on top of a legacy C++ API. I'll spare you the details of that, and just say the requirements boil down to:

    • JSON objects become Dictionary<string,object>.

    • JSON arrays become List<object>.

    • JSON values become the corresponding primitive CLR values.

    • The objects and arrays can be infinitely nested.

    I first deserialize the request string into a Newtonsoft JSON object and then call my method to convert in accordance with the above requirements:

    var jsonObject = JsonConvert.DeserializeObject(requestString);
    var apiRequest = ToApiRequest(jsonObject);
    // call the legacy C++ API ...
    

    Here is my method that converts to the structure the API expects:

        private static object ToApiRequest(object requestObject)
        {
            switch (requestObject)
            {
                case JObject jObject: // objects become Dictionary<string,object>
                    return ((IEnumerable<KeyValuePair<string, JToken>>) jObject).ToDictionary(j => j.Key, j => ToApiRequest(j.Value));
                case JArray jArray: // arrays become List<object>
                    return jArray.Select(ToApiRequest).ToList();
                case JValue jValue: // values just become the value
                    return jValue.Value;
                default: // don't know what to do here
                    throw new Exception($"Unsupported type: {requestObject.GetType()}");
            }
        }
    

    I hope that someone can find this approach useful.

    0 讨论(0)
  • 2020-12-01 03:36

    Alternative/Update:

    I needed to deserialize a dictionary of dictionaries of Strings and with current Json.NET (5.0) I did not had to create a CustomConverter, I just used (in VB.Net):

    JsonConvert.DeserializeObject(Of IDictionary(Of String, IDictionary(Of String, String)))(jsonString)
    

    Or, in C#:

    JsonConvert.DeserializeObject<IDictionary<String, IDictionary<String, String>>(jsonString);
    
    0 讨论(0)
提交回复
热议问题