反序列化为 JObject 时获取类型名称



有没有办法在使用反序列化时获取$type属性? 我在打开 TypeNameHandling 的情况下进行序列化,但是当我反序列化时,我没有包含类型信息的程序集。 我需要使用类型名称将其存储在正确的集合中,看起来$type没有带到 JObject。

编辑:如果我反序列化为 JObject,我可以得到$type,但如果我反序列化为将对象作为属性的类,则类型为 null。 不知道为什么它被剥离,因为$type存在于 json 中。 示例如下:

该类

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 属性:

var deserializedContainer = JsonConvert.DeserializeObject<Container>(json,
    new JsonSerializerSettings {
        MetadataPropertyHandling = MetadataPropertyHandling.Ignore
    });
var type = ((JObject) deserializedContainer.Test)["$type"];
// Type is Snarfblat

小提琴:https://dotnetfiddle.net/VBGVue

最新更新