【发布时间】:2020-12-25 16:10:35
【问题描述】:
我正在尝试将以下 JSON sn-ps 反序列化为结构 Shape 的 Vec:
use serde::{Deserialize, Serialize};
use serde_json::{Result, Value};
#[derive(Debug, Serialize, Deserialize)]
struct Shape { // this struct is not working, for display purpose only
shape_type: String,
d0: f64,
d1: f64,
d2: f64, //optional, like the case of "dot"
d3: f64, //optional, like the case of "circle"
}
let json = r#"
{[
["line", 1.0, 1.0, 2.0, 2.0],
["circle", 3.0, 3.0, 1.0],
["dot", 4.0, 4.0]
]}"#;
let data: Vec<Shape> = match serde_json::from_str(json)?;
显然,每种类型的Shape 都需要一个String 和不同数量的f64 来描述它。我应该如何定义Shape的结构来反序列化上面的JSON数据?
【问题讨论】:
-
您的 JSON 数据不是有效的 JSON。对象内部不能有匿名数组。另外,是否可以修改 JSON 格式,还是必须以当前形式反序列化?
-
我的错字。应该是
let json = r#"{"shapes": [["line", 1.0, 1.0, 2.0, 2.0], ..."#;不幸的是我无法更改 JSON 格式。我尝试将 d2 & d3 的类型更改为 Option,但没有运气: "invalid length 4, expected struct Shape with 5 elements"at line of "circle".
标签: json struct rust deserialization serde