如何在没有自定义反序列化器的情况下将 JSON 从同一 JSON 字典或数组反序列化为完全不同的类型?

问题描述 投票:0回答:1

如何将同一个 JSON 字典中的 JSON 反序列化为不同类型?

我必须将数据从 JSON 反序列化为 C#,这些数据可以是 JSON 字典中的许多不同类型,例如:

{
    "KEY1": { "mainType": "TYPE1", /* object of a specific type */ },
    "KEY2": { "mainType": "TYPE2", /* object of a similar but different type */ },
    "KEY3": { "mainType": "TYPE3", /* object of a very different type */ },
    "KEY4": { "mainType": "TYPE4", /* yet another completely different type */ },
    "KEY4": { "mainType": "TYPE5", /* another totally different type.... why? */ }
}

所有这些不同的类型都具有完全不同的属性,并且

mainType
属性告诉我们哪种类型是要反序列化的正确类型。

我不想编写自定义序列化器,我宁愿让

System.Text.Json
为我做。

我能够回答自己的问题,并想为其他人写下来(见下文):

c# json system.text.json
1个回答
0
投票

这里是一些解决此问题的示例

System.Text.Json
C#(使用 .NET 7+):

首先,创建一个所有其他类型都将继承的基类型,如果它们不共享任何属性也没关系:

public class BaseType 
{
    // any shared properties
}

接下来创建所有子类型:

public class Type1 : BaseType 
{ 
    // custom properties...
}
public class Type2 : BaseType 
{ }
public class Type3 : BaseType 
{ }
// ...etc

接下来,我们需要告诉

System.Text.Json
反序列化时派生类型是什么。将以下属性添加到基类中,以便
System.Text.Json
知道要反序列化为哪些类型:

using System.Text.Json.Serialization;

[JsonDerivedType(typeof(Type1), typeDiscriminator:"TYPE1")]
[JsonDerivedType(typeof(Type2), typeDiscriminator:"TYPE2")]
// ...etc
public class BaseType 
{
    ...
}

在我的例子中,类型鉴别器不是像“$type”这样的普通类型鉴别器名称,因此我必须通过添加此属性来告诉

System.Text.Json
要使用什么类型鉴别器属性名称:

[JsonPolymorphic(TypeDiscriminatorPropertyName = "mainType")]
public class BaseType 

为了反序列化完整的字典,我使用了以下代码:

using System.Text.Json;

var json = File.ReadAllText("test.json");
var dictionary = JsonSerializer.Deserialize< Dictionary<string, BaseType> >(json);
© www.soinside.com 2019 - 2024. All rights reserved.