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

如何修复JsonSerializationException:无法反序列化当前JSON对象错误

解决JsonSerializationException:无法将JSON对象反序列化为List类型

问题根源

返回的JSON是顶层对象(包含_total和users两个属性),但你尝试直接将其反序列化为List<UserData>数组类型,类型不匹配导致序列化失败。

原始JSON结构

{
  "_total": 3,
  "users": [
    {
      "username": "person1",
      "points": 3
    },
    {
      "username": "person2",
      "points": 2
    },
    {
      "username": "person3",
      "points": 1
    }
  ]
}

错误代码片段

原反序列化逻辑尝试直接将顶层JSON对象转为列表:

var data = JsonConvert.DeserializeObject<List<UserData>>(body); 

修复方案

方案1:创建匹配JSON结构的实体类(推荐)

定义对应顶层JSON对象的实体类,反序列化到该类后提取users列表:

// 新增顶层响应类,匹配JSON结构
public class UserListResponse
{
    public int _total { get; set; }
    public List<UserData> users { get; set; }
}

// 原UserData类保持不变
public class UserData
{
    public string username { get; set; }
    public int points { get; set; }
}

修改反序列化代码:

using (var response = await client.SendAsync(request))
{
    response.EnsureSuccessStatusCode();
    var body = await response.Content.ReadAsStringAsync();

    var responseData = JsonConvert.DeserializeObject<UserListResponse>(body); 
    foreach (UserData userdata in responseData.users) 
    {
        Debug.Log(userdata.username + ": " + userdata.points);
    }
}

方案2:直接解析JSON对象提取数组(无需新增类)

使用JObject解析顶层对象,提取users字段的JSON字符串后再反序列化为列表:

using Newtonsoft.Json.Linq;

using (var response = await client.SendAsync(request))
{
    response.EnsureSuccessStatusCode();
    var body = await response.Content.ReadAsStringAsync();

    var jsonObject = JObject.Parse(body);
    var usersJson = jsonObject["users"].ToString();
    var data = JsonConvert.DeserializeObject<List<UserData>>(usersJson);

    foreach (UserData userdata in data) 
    {
        Debug.Log(userdata.username + ": " + userdata.points);
    }
}

方案3:强制属性映射(不推荐)

若无法修改实体类结构,可通过JsonObjectAttribute强制映射,但该方式不符合JSON语义,仅作临时 workaround:

[JsonObject(MemberSerialization.OptIn)]
public class UserData
{
    [JsonProperty]
    public string username { get; set; }
    [JsonProperty]
    public int points { get; set; }
}

// 反序列化时配置忽略缺失成员
var settings = new JsonSerializerSettings
{
    MissingMemberHandling = MissingMemberHandling.Ignore
};
var data = JsonConvert.DeserializeObject<List<UserData>>(body, settings);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 00:50:20