问题
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