我正在编写C#来与第三方API接口.我在将一个特定的响应映射到一个类时遇到了问题.

该方法的doco说,响应将是:

{
    <text>:[{   /* driver ID */
        "t":<uint>, /* time of binding/unbinding*/
        "u":<long>  /* unit ID if binding, 0 if unbinding */
    }],
    ...
}

回答的例子是:{"2534":[{"t":1711353044,"u":10568}]}. 我定义了响应类和子类:

public class GetDriverBindingsResponse : IWialonApiRequestObject
{
    /// <summary>
    /// Collection of bindings.  The key is a Driver Id
    /// </summary>
    [JsonPropertyName("")]
    public Dictionary<string, List<DriverUnitBinding>>? Bindings { get; set; }
}

public class DriverUnitBinding
{
    /// <summary>
    /// time of binding/unbinding
    /// </summary>
    [JsonPropertyName("t")]
    public uint Time { get; set; }

    /// <summary>
    /// unit ID if binding, 0 if unbinding
    /// </summary>
    [JsonPropertyName("u")]
    public long UnitId { get; set; }
}

但是,在进行重命名时,绑定集合为null.即使是简单的测试也会失败:

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

我需要更改什么才能正确地反序列化这个类?

推荐答案

问题是您不能有一个空的属性名.序列化程序假定您正在反序列化100的JSON是您提供的类型.

在您的例子中,您可以直接将JSON反序列化为Dictionary<string, List<DriverUnitBinding>>:

string test = @"{""2534"":[{""t"":1711353044,""u"":10568}]}";
var x = JsonSerializer.Deserialize<Dictionary<string, List<DriverUnitBinding>>>(test);
Console.WriteLine(x?.Keys?.Count);

enter image description here

另一种 Select 是让GetDriverBindingsResponse简单地继承Dictionary<string, List<DriverUnitBinding>>类,尽管这可能不是最好的方法,除非这对您的数据模型有意义.

public class GetDriverBindingsResponse : Dictionary<string, List<DriverUnitBinding>>
{ }

Csharp相关问答推荐

EF Core在请求列表时忽略列,但在按ID获取时包含

如何注册接口类型,类型<>

从应用程序图API调用访问所有者字段

限制特定REST API不被访问,但部署代码

Azure Redis缓存与Entra ID身份验证

单元测试:模拟返回空

在swagger示例中添加默认数组列表

从VS调试器而不是测试资源管理器运行的调试NUnitDotNet测试

.NET并发词典交换值

在C#中,非静态接口方法的抽象和虚拟是冗余的吗?

将内置的OrderedEumable&Quot;类设置为内部类有什么好处?

在C#中,是否有与变量DISARD对应的C++类似功能?

为什么我不能从我的异步任务方法中返回异步任务方法?

ReadOnlyMemory访问基础索引的替代方案

如何使用EPPlus C#在单个单元格中可视化显示多行文字

基于C#方法的EF核心过滤查询(缓冲与流)

C#-如何将int引用获取到byte[]

Excel将';@';添加到具有范围的公式中

CsvHelper在第二次迭代时抛出System.ObjectDisposedException

将ValueTask发送给调用者