使用 system.text.json 时,可以通过 jsonserializeroptions 配置 typediscriminatorproperty 和 derivedtypes 来实现基于特定字段(如 type)的自动类型还原。具体做法是创建一个包含基类或接口属性的选项对象,注册所有可能的派生类型并指定其对应的鉴别器值,然后在反序列化时传入该选项,即可将 json 中的不同子类型准确还原为各自的 c# 实际类型。

如何配置 TypeDiscriminatorProperty 以支持多态反序列化?
在 System.Text.Json 中,启用多态反序列化的核心在于告诉序列化器哪个属性用于区分类型。通过设置 TypeDiscriminatorProperty 为某个属性名(例如 "type"),并在 DerivedTypes 集合中映射具体的派生类型及其鉴别器值,序列化器就能根据 JSON 数据中该字段的值选择正确的构造函数进行实例化。这种方法要求基类必须是 public 且具有可访问的默认构造函数,或者派生类的构造函数参数能与 JSON 属性一一匹配。

using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace PolymorphicDemo
{
public class Animal
{
[JsonPropertyName("name")]
public string Name { get; set; }
}
public class Dog : Animal
{
[JsonPropertyName("breed")]
public string Breed { get; set; }
}
public class Cat : Animal
{
[JsonPropertyName("color")]
public string Color { get; set; }
}
class Program
{
static void Main()
{
var options = new JsonSerializerOptions
{
WriteIndented = true,
TypeInfoResolver = new DefaultJsonTypeInfoResolver()
};
// 配置多态反序列化
options.TypeDiscriminatorProperty = "type";
options.DerivedTypes.Add(new JsonDerivedType(typeof(Dog), "dog"));
options.DerivedTypes.Add(new JsonDerivedType(typeof(Cat), "cat"));
string json = @"[
{ ""type"": ""dog"", ""name"": ""Buddy"", ""breed"": ""Labrador"" },
{ ""type"": ""cat"", ""name"": ""Whiskers"", ""color"": ""Black"" }
]";
List<animal> animals = JsonSerializer.Deserialize<list>>(json, options);
foreach (var animal in animals)
{
Console.WriteLine($"Type: {animal.GetType().Name}, Name: {animal.Name}");
if (animal is Dog dog) Console.WriteLine($" Breed: {dog.Breed}");
if (animal is Cat cat) Console.WriteLine($" Color: {cat.Color}");
}
}
}
}</list></animal>
如何处理未注册的派生类型或缺失鉴别器字段的情况?
当 JSON 数据中包含未在 DerivedTypes 中注册的鉴别器值,或者缺少指定的 TypeDiscriminatorProperty 字段时,System.Text.Json 默认会抛出 JsonException。为了避免程序崩溃,可以自定义 JsonConverter 来处理这些边缘情况,例如提供默认类型或忽略未知类型。此外,如果基类没有默认构造函数,必须确保所有派生类的构造函数都能被正确反射调用,否则也会引发异常。在实际开发中,建议对输入数据进行预校验或使用更灵活的转换器逻辑来增强鲁棒性。
exa-js 是 Exa 官方 JavaScript 软件开发工具包,Exa 是一个为 AI 工作流构建的网络搜索 API。它为代理提供了一种具体的方式来搜索网络、检索页面内容,并从代码中生成有来源的答案,而不是手动拼接原始 HTTP 调用。

using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace EdgeCaseDemo
{
public class BaseMessage
{
public string Content { get; set; }
}
public class TextMessage : BaseMessage
{
public string Text { get; set; }
}
public class ImageMessage : BaseMessage
{
public string Url { get; set; }
}
// 自定义转换器处理缺失 type 字段的情况
public class FlexibleMessageConverter : JsonConverter<basemessage>
{
public override BaseMessage Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
using var doc = JsonDocument.Parse(ref reader);
var root = doc.RootElement;
if (!root.TryGetProperty("type", out var typeProp))
{
// 如果没有 type 字段,默认为 TextMessage
return JsonSerializer.Deserialize<textmessage>(root.GetRawText(), options);
}
string typeValue = typeProp.GetString();
switch (typeValue)
{
case "text":
return JsonSerializer.Deserialize<textmessage>(root.GetRawText(), options);
case "image":
return JsonSerializer.Deserialize<imagemessage>(root.GetRawText(), options);
default:
throw new JsonException($"Unknown message type: {typeValue}");
}
}
public override void Write(Utf8JsonWriter writer, BaseMessage value, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
}
class Program
{
static void Main()
{
var options = new JsonSerializerOptions();
options.Converters.Add(new FlexibleMessageConverter());
string jsonWithMissingType = @"{ ""content"": ""Hello"", ""text"": ""Hi there"" }";
BaseMessage msg = JsonSerializer.Deserialize<basemessage>(jsonWithMissingType, options);
Console.WriteLine($"Deserialized as: {msg.GetType().Name}");
}
}
}</basemessage></imagemessage></textmessage></textmessage></basemessage>
当 JSON 数组中包含混合类型的元素时,反序列化结果列表的元素类型是什么?
当使用上述配置反序列化一个包含混合子类型元素的 JSON 数组时,返回的 List 中的每个元素实际上都是其对应的具体派生类型实例(如 Dog 或 Cat)。虽然列表的静态类型是基类 Animal,但在运行时,每个对象的实际类型由 JSON 中的 type 字段决定。这意味着你可以安全地对列表中的元素进行 is 检查或强制转换到具体的派生类型,而不会丢失任何数据。这种机制确保了类型信息的完整保留,使得后续的业务逻辑能够针对具体类型进行处理。










