try 将旧的ASP.NET Core项目从Newtonsoft.Json转换为System.Text.Json,但它更改了可为空的引用类型转换的行为.Json将可为空的引用类型序列化/反序列化为"{}",而不是"NULL".我该怎么修好它?我想摆脱Newtonsoft.Json.

services.AddMvc().AddNewtonsoftJson();

以下是该列表public IList<IDictionary<string, object>> List { get; set; }的类型.实际值类型为DBNull.

System.Text.Json

{
    "data": {
        "list": [
            {
                "headers": [],
                "list": [
                    {
                        "id": "3faab29e-982d-ccb9-197b-08db24ef09e7",
                        "contractType": "Basis",
                        "tEvent": "Edit",
                        "Basis": 0.0000,
                        "fees": {},
                        "FlatPrice": {},
                        "theirContract": {}
                    },

Newtonsoft.Json

{
    "data": {
        "list": [
            {
                "headers": [],
                "list": [
                    {
                        "id": "3faab29e-982d-ccb9-197b-08db24ef09e7",
                        "contractType": "Basis",
                        "tEvent": "Edit",
                        "Basis": 0.0000,
                        "fees": null,
                        "FlatPrice": null,
                        "theirContract": null
                    },

推荐答案

在 compose 本报告时,有System.Text.Json does not have built-in support for DBNull个.

相反,您可以编写一个自定义JsonConverter来处理DBNull个值,方法是覆盖转换器的Write()方法以打印出JSON文本null:

public class DBNullJsonConverter : JsonConverter<DBNull> 
{ 
    public override bool CanConvert(Type typeToConvert) 
    { 
        return typeToConvert == typeof(DBNull); 
    } 
 
    public override DBNull Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) 
    { 
        throw new NotImplementedException(); 
    } 
 
    public override void Write(Utf8JsonWriter writer, DBNull value, JsonSerializerOptions options) 
    { 
        // write the JSON literal null
        writer.WriteNullValue(); 
    } 
}

然后,将此转换器传递给您的JsonSerializer中的JsonSerializerOptions:

var options = new JsonSerializerOptions();
options.Converters.Add(new DBNullJsonConverter());

// you should get null for fields of type DBNull here
var json = JsonSerializer.Serialize(someObject, options);

Csharp相关问答推荐

始终保留数组中的最后N个值,丢弃最老的

如何在C#中将对象[*,*]直接转换为字符串[*,*]?

碰撞检测与盒碰撞器,其isTrigger on问题

在一个模拟上设置一个方法,该模拟具有一个参数,该参数是一个numc函数表达式

不带身份的Blazor服务器.Net 8 Cookie身份验证

Azure Redis缓存与Entra ID身份验证

只有第一个LINQ.Count()语句有效

Rx.Net窗口内部可观测数据提前完成

在.NET 8最低API中从表单绑定中排除属性

RabbitMQ群集的MassTransit配置问题

.NET 8在appsettings.json中核心使用词典URI、URI&>

将FileStream的特定部分作为字节数组读取

C#中类库项目的源代码生成器

如何在Polly重试策略成功之前将HttpClient请求排队?

将两个for循环更改为一条LINQ语句

为什么连接到Google OAuth2后,结果.Credential为空?

C#定时器回调对象上下文?

SharpZipLib在文件名前加上目录名,生成tar.gz

反序列化我以前使用System.Text.Json序列化的文件时出现异常

根据运行时值获取泛型类型的字典