.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
相关产品推荐
相关产品推荐

