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

如何使用Serde解析包含可变长度数组的JSON?

解决Serde解析可变长度JSON数组的问题

你遇到的错误是因为在Rust中,[Option<Device>]属于动态大小类型(DST),结构体无法直接持有这类字段——结构体需要固定的内存布局,而动态数组的大小在编译时无法确定,Serde也无法完成这类类型的反序列化。

修正方案

把结构体中的动态数组类型替换为Vec<Option<Device>>,Vec是Rust标准库提供的动态长度容器,Serde原生支持将JSON数组反序列化为Vec:

#[derive(Debug, Deserialize)]
pub struct Device {
    pub path: String,
    pub start_sector: Option<u64>,
    pub end_sector: Option<u64>,
}

#[derive(Debug, Deserialize)]
pub struct Config {
    pub hostname: String,
    pub devices: Vec<Option<Device>>,
}

额外说明

如果JSON中的devices字段是可选的(即可能不存在),可以进一步将其包装为Option<Vec<Option<Device>>>:

#[derive(Debug, Deserialize)]
pub struct Config {
    pub hostname: String,
    pub devices: Option<Vec<Option<Device>>>,
}

这样修改后,Serde就能正常解析包含可变长度数组的JSON数据了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 04:16:09