【问题标题】:Get type name when deserializing to JObject反序列化为 JObject 时获取类型名称
【发布时间】:2014-02-24 22:42:29
【问题描述】:

在使用 Deserialize 时有没有办法获取 $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

【问题讨论】:

    标签: c# json.net


    【解决方案1】:

    您可以通过在反序列化时将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

    【讨论】:

    • 有趣的是,如果我反序列化为 JObject 而不是包含对象的类,我可以获得类型。查看我的更新。
    猜你喜欢
    • 2017-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-18
    • 2014-10-06
    • 1970-01-01
    • 2023-03-16
    相关资源
    最近更新 更多