How can I deserialize a child instance as a parent object without losing its specific property?

别说谁变了你拦得住时间么 提交于 2019-12-06 01:19:22

If the situation arises in only a few cases, do serialize into a DTO (Data Transfer Object) class that has both properties. If you don't want to bother creating a new named class, you can also use an anonymous class that will do the job for you

var myDto = JsonConvert.DeserializeAnonymousType(jsonString,
    new {
        PropertyB = new {
            GenProp ="",
            SpecPropB1 ="",
            SpecPropB2 = ""}
        });

If the case arrises too frequently, that is if you are unsure of the schema of the json you're deserializing, you can deserialize into a JObject, and then query if fields are present or not.

B b;
JObject o = JObject.Parse(jsonString);

// I need this variable to compile, but I won't use it.
JToken _;
if(o.TryGetValue("SpecPropB1", out _)
{
    b = o.ToObject<B1>();
}
else
{
//...
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!