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

MAUI原生iOS项目中ServiceStack.Text v8.3.0序列化异常问题

解决.NET 8 MAUI iOS真机集成ServiceStack.Text时的IList<>类型异常

问题核心

该异常是ServiceStack.Text在.NET MAUI iOS真机的AOT编译环境下的类型检测bug,误将普通实体类UserRequest识别为IList<>类型导致,仅在AOT编译的真机触发,JIT模式的模拟器不受影响,调用API或直接序列化/反序列化操作都会触发异常。

解决方案

1. 检查实体类定义

确认UserRequest类未继承任何集合接口(如IList<>),也不存在易被误判的命名/结构:

// 正确的普通实体类示例
public class UserRequest
{
    public int UserId { get; set; }
    public string Username { get; set; }
    // 其他业务属性
}

避免类名包含List/Collection等集合相关后缀,防止序列化器误识别。

2. 显式配置序列化规则

在App启动阶段(如MauiProgram.cs的CreateMauiApp方法中)添加序列化配置,强制将UserRequest视为普通引用类型:

// 针对UserRequest的单独配置
ServiceStack.Text.JsConfig<UserRequest>.TreatValueAsRefType = true;

// 或全局配置,避免类型信息干扰
ServiceStack.Text.JsConfig.IncludeTypeInfo = false;

3. 配置AOT编译兼容规则

MAUI iOS真机的AOT编译会裁剪未被显式引用的类型,导致ServiceStack.Text的类型检测逻辑失效。在项目的.csproj文件中添加以下配置,保留ServiceStack.Text的必要类型:

<ItemGroup>
    <TrimmerRootAssembly Include="ServiceStack.Text" />
    <AotAssemblies Include="ServiceStack.Text" />
</ItemGroup>

4. 临时Workaround(绕过ServiceStack客户端自动序列化)

如果以上方案无效,可手动处理序列化与请求发送:

// 手动序列化请求对象
var requestJson = ServiceStack.Text.JsonSerializer.SerializeToString(user);

// 使用HttpClient发送请求
var httpClient = new HttpClient();
var requestContent = new StringContent(requestJson, Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync("你的API地址", requestContent);

// 手动反序列化响应
var responseJson = await response.Content.ReadAsStringAsync();
var userResponse = ServiceStack.Text.JsonSerializer.DeserializeFromString<UserResponse>(responseJson);

内容的提问来源于stack exchange,提问作者komal kadam

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 11:05:06