You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 8升级后JObject跨服务传输序列化数据丢失问题

.NET 8升级后JObject跨服务传输异常的解决办法

问题根源

.NET 8对System.Text.Json的第三方类型序列化逻辑做了严格调整,而你同时混用了:

  • Newtonsoft.Json的JObject类型字段
  • System.Text.Json的JsonPropertyName特性

两者的序列化规则不兼容,导致跨服务传输时(通过System.Text.Json序列化/反序列化),JObject的结构被错误解析,出现type为空数组、data多层空嵌套这类异常。

可行解决方案

1. 统一使用Newtonsoft.Json生态

将字段特性替换为Newtonsoft.Json的JsonProperty,并确保服务间的序列化/反序列化都使用Newtonsoft.Json:

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public class A
{
    [JsonProperty("metadata")]
    public JObject Metadata { get; set; }
}

2. 为System.Text.Json自定义JObject转换器

编写一个转换器让System.Text.Json能正确处理JObject,避免解析错误:

using System.Text.Json;
using System.Text.Json.Serialization;
using Newtonsoft.Json.Linq;

public class JObjectConverter : JsonConverter<JObject>
{
    public override JObject Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        using var doc = JsonDocument.ParseValue(ref reader);
        return JObject.Parse(doc.RootElement.GetRawText());
    }

    public override void Write(Utf8JsonWriter writer, JObject value, JsonSerializerOptions options)
    {
        writer.WriteRawValue(value.ToString(Newtonsoft.Json.Formatting.None));
    }
}

然后在字段上标记使用该转换器:

using System.Text.Json.Serialization;
using Newtonsoft.Json.Linq;

public class A
{
    [JsonPropertyName("metadata")]
    [JsonConverter(typeof(JObjectConverter))]
    public JObject Metadata { get; set; }
}

3. 替换JObject为System.Text.Json原生类型

将JObject换成JsonElement(兼容所有.NET版本)或JsonObject(.NET 7+支持),完全使用System.Text.Json生态:

using System.Text.Json;
using System.Text.Json.Serialization;

public class A
{
    [JsonPropertyName("metadata")]
    public JsonElement Metadata { get; set; }
    // .NET 7+可替换为:
    // public JsonObject Metadata { get; set; }
}

内容的提问来源于stack exchange,提问作者Vagner Wentz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 17:09:56