问题描述
使用Deserialize时是否可以获取$ type属性?我使用TypeNameHandling进行序列化,但是当我反序列化时,我没有包含类型信息的程序集.我需要使用Type名称将其存储在正确的集合中,看起来$ type不会被带到JObject中.
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.
如果我反序列化为JObject,则可以获得$ type,但是如果我反序列化为以对象为属性的类,则该类型为null.不知道为什么在json中会因为$ type而将其剥离.下面的示例:
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:
班级
public class Container {
public object Test { get; set; }
}
反序列化代码
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
推荐答案
在反序列化时,可以通过将MetadataPropertyHandling
设置为Ignore
来防止Json.Net使用$type
属性:
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
提琴: https://dotnetfiddle.net/VBGVue
这篇关于反序列化为JObject时获取类型名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!