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

.NET 8 MAUI Blazor Hybrid iOS发布模式序列化异常求助

.NET 8 MAUI Blazor Hybrid iPad发布模式Json序列化异常解决方案

针对仅iPad发布模式下System.Text.Json序列化抛出NullabilityInfoContext_NotSupported异常的问题,可尝试以下几种解决方案:

方案1:手动配置Json序列化选项,绕过NullabilityInfoContext检测

由于发布模式下iOS的AOT编译和代码修剪会导致NullabilityInfoContext无法正常工作,可通过手动指定属性可空性的方式,避免依赖该上下文:

// 在MauiProgram.cs或序列化配置处创建自定义Json选项
var jsonOptions = new JsonSerializerOptions
{
    TypeInfoResolver = new DefaultJsonTypeInfoResolver
    {
        Modifiers = { typeInfo =>
            {
                foreach (var property in typeInfo.Properties)
                {
                    // 手动判断属性可空性,不依赖NullabilityInfoContext
                    property.IsNullable = property.PropertyType.IsNullableValueType() 
                        || !property.PropertyType.IsValueType;
                }
            }
        }
    }
};

// 注册为服务,供整个应用使用
builder.Services.AddSingleton(jsonOptions);

方案2:调整iOS发布模式的编译与修剪配置

修改项目的csproj文件,针对iOS发布模式保留System.Reflection和System.Text.Json的必要反射信息,避免代码修剪移除关键类型:

<PropertyGroup Condition="'$(TargetFramework)' == 'net8.0-ios' and '$(Configuration)' == 'Release'">
    <!-- 保留System.Reflection和System.Text.Json的完整程序集 -->
    <TrimmerRootAssembly>System.Reflection</TrimmerRootAssembly>
    <TrimmerRootAssembly>System.Text.Json</TrimmerRootAssembly>
    <!-- 禁用对特定属性的修剪,确保Nullability相关元数据保留 -->
    <AssemblyAttributeTrimmer>false</AssemblyAttributeTrimmer>
</PropertyGroup>

注意:此方案可能会略微增大IPA包体积,但能有效解决反射依赖问题。

方案3:替换为Newtonsoft.Json序列化库

如果上述方案仍无法解决问题,可考虑切换到兼容性更好的Newtonsoft.Json(Json.NET),它不依赖NullabilityInfoContext:

  1. 安装NuGet包:Newtonsoft.Json
  2. 将所有使用System.Text.Json的序列化/反序列化代码替换为Newtonsoft.Json的实现,例如:
    // 原System.Text.Json代码
    // var json = JsonSerializer.Serialize(obj);
    // var obj = JsonSerializer.Deserialize<T>(json);
    
    // 替换为Newtonsoft.Json
    var json = JsonConvert.SerializeObject(obj);
    var obj = JsonConvert.DeserializeObject<T>(json);
    

内容的提问来源于stack exchange,提问作者John Alexander

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 19:17:11