How to cast JObject in JSON.Net to T

前端 未结 2 1770
天涯浪人
天涯浪人 2020-12-17 08:52

I know that I can use JsonConvert.DeserializeObject(string), however, I need to peek into the object\'s _type (which may not be the first

相关标签:
2条回答
  • 2020-12-17 09:30

    JSON.NET has no direct ability to support both requisites:

    • custom name of the property holding the type name
    • look for the property anywhere in the object

    The first requisites is fulfilled by JsonSubTypes The second one by specifying thh right MetadataPropertyHandling

    0 讨论(0)
  • 2020-12-17 09:40

    First parse the JSON into a JObject. Then lookup the _type attribute using LINQ to JSON. Then switch depending on the value and cast using ToObject<T>:

    var o = JObject.Parse(text);
    var jsonType = (String)o["_type"];
    
    switch(jsonType) {
        case "something": return o.ToObject<Type>();
        ...
    }
    
    0 讨论(0)
提交回复
热议问题