加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何在反序列化期间忽略$type

发布时间:2020-12-15 23:34:44 所属栏目:百科 来源:网络整理
导读:我有2个这样的课程 class A: Base{ public string CommonField; public int IntField;}class B: Base{ public string CommonField; public double DoubleField;} 我序列化一个具有类型名称处理的实例 { "$type": "MyApp.A,MyApp","CommonField": "SomeValue"
我有2个这样的课程

class A: Base
{
    public string CommonField;
    public int IntField;
}

class B: Base
{
    public string CommonField;
    public double DoubleField;
}

我序列化一个具有类型名称处理的实例

{
  "$type": "MyApp.A,MyApp","CommonField": "SomeValue","IntField": 123,"SomeBaseField": 321
}

从中获取B实例的最简单方法是什么?在你问为什么之前,它是关于将A作为B导入(它们具有基本属性以及那些名称与你看到的匹配,所以这个操作是合理的).

尝试反序列化给定的json,因为B将抛出

Newtonsoft.Json.JsonSerializationException: Type specified in JSON 'MyApp.A,MyApp,Version=0.0.1.1,Culture=neutral,PublicKeyToken=null' is not compatible with 'MyApp.B,PublicKeyToken=null'. Path '$type',line 2,position 42.
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ResolveTypeName(JsonReader reader,Type& objectType,JsonContract& contract,JsonProperty member,JsonContainerContract containerContract,JsonProperty containerMember,String qualifiedTypeName)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadMetadataProperties(JsonReader reader,Object existingValue,Object& newValue,String& id)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader,Type objectType,JsonContract contract,Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader,Boolean checkAdditionalContent)

我能想到以下几点:

>将json反序列化为A,创建B的实例并复制所有值(坏);
>替换(甚至删除?)$在json中键入并尝试将其反序列化为B(更好,仍然不好);
>使用SerializationBinder并将json反序列化为B(好):

public class JsonABBinder : DefaultSerializationBinder
{
    public override Type BindToType(string assemblyName,string typeName)
    {
        if (typeName == "MyApp.A")
             return typeof(B);
        return base.BindToType(assemblyName,typeName);
    }
}

还有更好的方法吗?在我的场景中,有许多这样的类型,并且对这些绑定器的追求(以及首先读取json作为A以确定应用哪个绑定器)非常繁琐.

我正在寻找一种简单的方法来忽略$type并直接指定所需类型(泛型方法),因为我知道我需要的类型,但我不知道json中的哪种类型,我想忽略它.

解决方法

您可以使用:

new JsonSerializer().TypeNameHandling = TypeNameHandling.None

这将忽略$type.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读