Get type name when deserializing to JObject

北慕城南 提交于 2019-12-10 16:28:25

问题


Is there a way to get the $type property when using Deserialize ? I serialize with TypeNameHandling on, but when I deserialize, I don't have the assemblies that contain the type information. I need to use the Type name to store it in the right collection, it looks like $type is not brought over to the JObject.

Edit: If I deserialize as a JObject, I can get the $type, but if I deserialize as a class that has an object as a property, the type is null. Not sure why its getting stripped out as the $type exists in the json. Example below:

The class

public class Container {
    public object Test { get; set; }
}

And the deserilization code

var container = new Container {
    Test = new Snarfblat()
};


var json = JsonConvert.SerializeObject(container, 
new JsonSerializerSettings {
    TypeNameHandling = TypeNameHandling.Objects
});
var deserializedContainer = JsonConvert.DeserializeObject<Container>(json);

var type = ((JObject) deserializedContainer.Test)["$type"];
// Type is null

var deserializedContainer2 = JsonConvert.DeserializeObject<JObject>(json);

var type2 = deserializedContainer2["Test"]["$type"];
// Type is snarfblat

回答1:


You can prevent Json.Net from consuming the $type property by setting MetadataPropertyHandling to Ignore when you deserialize:

var deserializedContainer = JsonConvert.DeserializeObject<Container>(json,
    new JsonSerializerSettings {
        MetadataPropertyHandling = MetadataPropertyHandling.Ignore
    });

var type = ((JObject) deserializedContainer.Test)["$type"];
// Type is Snarfblat

Fiddle: https://dotnetfiddle.net/VBGVue



来源:https://stackoverflow.com/questions/22000711/get-type-name-when-deserializing-to-jobject

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!