.NET7 Android中序列化继承Java.Lang.Object的对象抛System.Text.Json异常
解决System.Text.Json序列化继承Java.Lang.Object对象的问题
核心原因
异常是因为Java.Lang.Object基类包含与System.Type相关的成员,这类成员触发了System.Text.Json的不支持类型序列化限制。我们需要排除基类成员的序列化,只处理自定义子类的属性。
方案1:通过JsonSerializerOptions过滤子类专属属性
在序列化时配置选项,只保留当前子类声明的属性,排除基类的所有成员:
var serializeOptions = new JsonSerializerOptions { TypeInfoResolver = new DefaultJsonTypeInfoResolver { Modifiers = { typeInfo => { // 替换成你的自定义类类型 if (typeInfo.Type == typeof(YourCustomJavaDerivedClass)) { // 移除所有非当前类声明的属性(即基类Java.Lang.Object的属性) typeInfo.Properties.RemoveAll(p => p.DeclaringType != typeof(YourCustomJavaDerivedClass)); } } } } }; // 使用配置好的选项序列化 string json = JsonSerializer.Serialize(yourObjectInstance, serializeOptions);
方案2:自定义JsonConverter控制序列化逻辑
编写自定义转换器,手动处理子类属性的序列化与反序列化,完全跳过基类:
public class CustomJavaObjectConverter<T> : JsonConverter<T> where T : Java.Lang.Object, new() { public override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { var obj = new T(); using var jsonDoc = JsonDocument.ParseValue(ref reader); var root = jsonDoc.RootElement; // 遍历子类的所有属性,逐一赋值 foreach (var prop in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) { if (root.TryGetProperty(prop.Name, out var element)) { var value = JsonSerializer.Deserialize(element.GetRawText(), prop.PropertyType, options); prop.SetValue(obj, value); } } return obj; } public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) { writer.WriteStartObject(); // 只序列化子类自身声明的公共属性 foreach (var prop in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) { var propValue = prop.GetValue(value); writer.WritePropertyName(prop.Name); JsonSerializer.Serialize(writer, propValue, prop.PropertyType, options); } writer.WriteEndObject(); } }
使用时在选项中注册转换器:
var options = new JsonSerializerOptions(); options.Converters.Add(new CustomJavaObjectConverter<YourCustomJavaDerivedClass>()); string json = JsonSerializer.Serialize(yourObjectInstance, options);
方案3:检查并忽略子类中的System.Type类型属性
如果你的自定义子类中自己定义了System.Type类型的属性,直接给该属性标记[JsonIgnore]特性即可避免异常:
public class YourCustomJavaDerivedClass : Java.Lang.Object { public string Name { get; set; } // 忽略导致序列化失败的Type类型属性 [JsonIgnore] public Type SomeTypeProperty { get; set; } }
内容的提问来源于stack exchange,提问作者Magik
相关产品推荐
相关产品推荐

