我想提取有关 json 字符串的一些信息,但当我尝试这样做时遇到一些问题。
这是我的json格式字符串的样式:
{
"id": "my_id",
"field1": {
"value": true,
"test": true
},
"target": {
"value1": "value",
"value2": 0,
"value3": true,
"test": false
},
"field2": [
"value"
],
"files": [
"this/is/my/path"
]
}
{
"id": "my_id",
"field1": {
"value": true,
"test": true
},
"target": {
"value1": "value",
"value2": 30,
"value3": false,
"test": false
},
"field2": [
"value"
],
"files": [
"this/is/my/path"
]
}
{
"id": "my_id",
"field1": {
"value": true,
"test": true
},
"target": {
"value1": "value",
"value2": 10,
"value3": true,
"test": true
},
"field2": [
"value"
],
"files": [
"this/is/my/path"
]
}
对于每个对象,我想提取目标和文件路径中的测试字段。
为此我尝试:
#[derive(Debug, Serialize, Deserialize)]
struct AllFiles {
target: Target,
files: Vec<String>
}
#[derive(Debug, Serialize, Deserialize)]
struct Target {
test: bool
}
fn main() {
let json = "JSON string above ^^^";
let all_files: Vec<AllFiles> = serde_json::from_str(json).unwrap();
}
但是我有这个错误:
Error("invalid type: map, expected a sequence", line: 1, column: 0)'
我不知道如何管理它。 最后我想要 Vec,这样我就可以浏览它并测试它的每个对象
谁能帮我解决这个问题吗?
我尝试在 Rust Playground 上重现您的问题,并且此代码运行正确。我假设您的数据包含在一个数组中,并且我还更改了路径字符串以在末尾包含一个数字,以便更好地可视化结果。你可以试试这里
use serde::{Serialize, Deserialize};
#[derive(Debug, Serialize, Deserialize)]
struct AllFiles {
target: Target,
files: Vec<String>
}
#[derive(Debug, Serialize, Deserialize)]
struct Target {
test: bool
}
fn main() {
let json = r#"[
{
"id": "my_id",
"field1": {
"value": true,
"test": true
},
"target": {
"value1": "value",
"value2": 0,
"value3": true,
"test": false
},
"field2": [
"value"
],
"files": [
"this/is/my/path1"
]
},
{
"id": "my_id",
"field1": {
"value": true,
"test": true
},
"target": {
"value1": "value",
"value2": 0,
"value3": true,
"test": false
},
"field2": [
"value"
],
"files": [
"this/is/my/path2"
]
},
{
"id": "my_id",
"field1": {
"value": true,
"test": true
},
"target": {
"value1": "value",
"value2": 10,
"value3": true,
"test": true
},
"field2": [
"value"
],
"files": [
"this/is/my/path3"
]
}
]"#;
let all_files: Vec<AllFiles> = serde_json::from_str(json).unwrap();
for item in all_files {
println!("{:?}", item);
}
}