gpt4 book ai didi

json - 将多个JSON字段反序列化为Serde中的单个Vec

转载 作者:行者123 更新时间:2023-12-03 11:48:02 25 4
gpt4 key购买 nike

您能帮我解决以下问题吗?
我有一个JSON:

{
"some_other_field": "value",
"option1": "value1",
"option2": "value2",
[...]
"option10": "value10",
}
最多X个 optionX字段都是可选的
我想将其反序列化为具有单个 Vec<String>的结构,其中向量中的索引对应于字段名称中的后缀:
options[1] -> value of `option1`
options[10] -> value of `option10`
这是我的结构:
struct Data {
some_other_field: String,
options: Vec<String>,
}
我尝试了很多事情,包括编写自定义反序列化器,但我无法通过此问题:(
任何帮助将不胜感激。

最佳答案

解决此问题的一种方法是使用serde_json序列化JSON数据,然后使用临时映射选择这些值。我跳过了很多错误检查,但是这里是概述:

use serde_json::{Result, Value};
use std::collections::HashMap;

#[derive(Debug)]
struct Data {
some_other_field: String,
options: Vec<String>,
}

fn text_to_data(text: &str) -> Result<Data> {
let prefix: &'static str = "option";

// Deserialize JSON
let value: Value = serde_json::from_str(text)?;
let value_map = value.as_object().unwrap();

// Filter keys for "option*", cut prefix, convert to integer and store it in a map
let options_map: HashMap<usize, &str> = value_map.iter()
.filter(|it| it.0.starts_with(prefix))
.map(|it| (it.0[prefix.len()..].parse::<usize>().unwrap(), it.1.as_str().unwrap()))
.collect();

// Get the maximum of options
let options_count = options_map.iter().map(|it| it.0).max().unwrap();

// Collect values to a vector or use empty string as default
let options: Vec<String> = (0..=*options_count)
.map(|it| options_map.get(&it).unwrap_or(&"").to_string()).collect();

// Also access other fields in JSON
let some_other_field =
value.get("some_other_field").unwrap().as_str().unwrap().to_string();

Ok(Data { some_other_field, options })
}


fn main() {
let data = r#"
{
"some_other_field": "value",
"option1": "value1",
"option2": "value2",
"option10": "value10"
}"#;

let x = text_to_data(data);
println!("{:?}", x);
}

输出:
Ok(Data { some_other_field: "value", options: ["", "value1", "value2", "", "", "", "", "", "", "", "value10"] })

关于json - 将多个JSON字段反序列化为Serde中的单个Vec,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63260359/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com