反序列化JSON递归到IDictionary的<字符串对象>

问题描述:

我试图将一些旧的工作中使用Newtonsoft JSON.NET。使用 System.Web.Script.Serialization.JavaScriptSerializer.Deserialize 方法(例如,如果没有指定目标类型)的默认处理返回词典&LT ;字符串对象> 的内部对象

I'm trying to convert some older work to use Newtonsoft JSON.NET. The default handling using the System.Web.Script.Serialization.JavaScriptSerializer.Deserialize method (e.g. if no target type is specified) is to return a Dictionary<string,object> for inner objects.

这实际上是JSON一个真正有用的基本类型,因为它也恰好是基础类型使用 ExpandoObjects ,并且是动态类型是最明智的内部实现。

This is actually a really useful basic type for JSON since it also happens to be the underlying type used by ExpandoObjects and is the most sensible internal implementation for dynamic types.

如果我指定这种类型的,例如:

If I specify this type, e.g.:

 var dict = JsonConvert.DeserializeObject<Dictionary<string,object>>(json);



JSON.NET将正确地反序列化最外层的对象结构,但它返回一个 JObject 键入任何内部结构。我真正需要的是用于任何内对象类型结构相同的外部结构

JSON.NET will deserialize the outermost object structure correctly, but it returns a JObject type for any inner structures. What I really need is for the same outer structure to be used for any inner object-type structures.

是否有指定的类型的方式以用于内的对象,而不仅仅是最外层类型回来了?

Is there a way to specify a type to be used for inner objects, and not just the outermost type returned?

在反序列化使用JSON的复杂的对象,你需要添加一个JsonSerializer设置的参数。这将确保所有的内部类型的得到适当的反序列化。

When Deserializing your complex objects using Json, you need to add a JsonSerializer Settings as a parameter. This will ensure that all of the inner types get deserialized properly.

    private JsonSerializerSettings _jsonSettings = new JsonSerializerSettings
    {
        TypeNameHandling = TypeNameHandling.All,
        TypeNameAssemblyFormat = FormatterAssemblyStyle.Full
    };

当序列化你的对象,你可以使用SerializerSettings:

When Serializing your object, you can use the SerializerSettings:

    string json= JsonConvert.SerializeObject(myObject, _jsonSettings)

然后当你反序列化,使用:

Then when you are deserializing, use:

    var dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(json, _jsonSettings);



此外,当您序列化时,JsonSerializerSettings添加到您的SerializeObject(对象设置)

Also, when you serialize, add the JsonSerializerSettings to your SerializeObject(object, settings)

编辑:您还可以更改TypeNameHandling和TypeNameAssemblyFormat如果您需要。我把它们设置为所有和全分别以保证我的复杂对象被序列,毫无疑问正确的反序列化,但智能感知为您提供了其他选择

You can also change the TypeNameHandling and TypeNameAssemblyFormat if you need to. I have them set at 'All' and 'Full' respectively to ensure that my complex objects get serialized and deserialized properly without doubt, but intellisense provides you with other alternatives