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

C#使用System.Text.Json反序列化第三方API响应失败问题

解决方法

你的问题在于JSON的顶级结构是动态键值对(driver ID为键),但你当前的类试图用标记了[JsonPropertyName("")]的Bindings属性捕获数据——这是错误的,因为JSON中并没有名为空字符串的键,直接导致反序列化无法匹配到数据。

你可以通过以下两种方式修复:

方案1:让响应类直接继承字典类型

最简单的方式是让GetDriverBindingsResponse直接继承Dictionary<string, List<DriverUnitBinding>>,这样整个JSON对象会直接映射为字典:

public class GetDriverBindingsResponse : Dictionary<string, List<DriverUnitBinding>>, IWialonApiRequestObject
{
    // 保留接口要求的其他成员(如果有)
}

public class DriverUnitBinding
{
    [JsonPropertyName("t")]
    public uint Time { get; set; }

    [JsonPropertyName("u")]
    public long UnitId { get; set; }
}

测试代码验证:

string test = "{\"2534\":[{\"t\":1711353044,\"u\":10568}]}";
GetDriverBindingsResponse? x = JsonSerializer.Deserialize<GetDriverBindingsResponse>(test);
Console.WriteLine(x?.Count); // 输出1

方案2:使用JsonExtensionData属性捕获动态键

如果需要保留Bindings属性的结构,可以用[JsonExtensionData]标记字典属性,自动捕获所有未匹配的顶级键值对:

public class GetDriverBindingsResponse : IWialonApiRequestObject
{
    [JsonExtensionData]
    public Dictionary<string, JsonElement>? Bindings { get; set; }

    // 可选:添加辅助属性将JsonElement转换为强类型列表
    public Dictionary<string, List<DriverUnitBinding>>? TypedBindings => Bindings?.ToDictionary(
        kvp => kvp.Key,
        kvp => JsonSerializer.Deserialize<List<DriverUnitBinding>>(kvp.Value)
    );
}

public class DriverUnitBinding
{
    [JsonPropertyName("t")]
    public uint Time { get; set; }

    [JsonPropertyName("u")]
    public long UnitId { get; set; }
}

测试时访问强类型数据:

string test = "{\"2534\":[{\"t\":1711353044,\"u\":10568}]}";
GetDriverBindingsResponse? x = JsonSerializer.Deserialize<GetDriverBindingsResponse>(test);
Console.WriteLine(x?.TypedBindings?.Count); // 输出1

关键说明

  • [JsonPropertyName("")]仅适用于固定名称的空字符串键,但你的JSON中没有这类键,而是动态的driver ID,因此完全不适用。
  • 方案1更直接,适合无需额外属性的场景;方案2保留类结构,适合需要在响应类中添加其他成员的情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 09:26:01