json - 以不同的格式反序列化 JSON - Serde_JSON

标签 json rust serde-json

我正在尝试从具有以下维度的 Rust 文件中读取 JSON:

{
    "DIPLOBLASTIC":"Characterizing the ovum when it has two primary germinallayers.",
    "DEFIGURE":"To delineate. [Obs.]These two stones as they are here defigured. Weever.",
    "LOMBARD":"Of or pertaining to Lombardy, or the inhabitants of Lombardy.",
    "BAHAISM":"The religious tenets or practices of the Bahais."
}

我想将每个单词及其描述存储在一个向量中(这是一个刽子手游戏)。如果文件格式如下,我可以读取文件:

[
    {
        "word": "DIPLOBLASTIC",
        "description": "Characterizing the ovum when it has two primary germinallayers."
    },
    {
        "word": "DEFIGURE",
        "description": "To delineate. [Obs.]These two stones as they are here defigured. Weever."
    }
]

我使用以下代码执行此操作:

#[macro_use]
extern crate serde_derive;

use serde_json::Result;
use std::fs;

#[derive(Deserialize, Debug)]
struct Word {
    word: String,
    description: String,
}

fn main() -> Result<()> {
    let data = fs::read_to_string("src/words.json").expect("Something went wrong...");
    let words: Vec<Word> = serde_json::from_str(&data)?;
    println!("{}", words[0].word);
    Ok(())
}

但是,在第二个 JSON 示例中,我试图找出如何保留 JSON 文件的原始格式而不将其转换为单词和描述。

有没有办法使用现有的 JSON 格式,或者我需要重新格式化它吗?

最佳答案

您可以将 map 收集到 HashMapBTreeMap 中,然后使用它的键值对来制作单词向量。

fn main() -> Result<()> {
    let data = r#"{
        "DIPLOBLASTIC":"Characterizing the ovum when it has two primary germinallayers.",
        "DEFIGURE":"To delineate. [Obs.]These two stones as they are here defigured. Weever.",
        "LOMBARD":"Of or pertaining to Lombardy, or the inhabitants of Lombardy.",
        "BAHAISM":"The religious tenets or practices of the Bahais."
    }"#;
    let words: std::collections::BTreeMap<String, String> = serde_json::from_str(data)?;
    let words = words
        .into_iter()
        .map(|(word, description)| Word { word, description })
        .collect::<Vec<_>>();
    println!("{:#?}", words);
    Ok(())
}

关于json - 以不同的格式反序列化 JSON - Serde_JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70656234/

相关文章:

json - 如何测试 WCF JSON 服务 - 单元测试

java - 向 JSONObject 添加数据

rust - 为什么 map 和 map_err 捕获同一个变量?

rust - 函数返回 serde 反序列化类型时如何修复生命周期错误?

json - 使用 serde_json 解析对象内部的对象

c# - 用于 PCI 合规性的敏感数据的自定义 JSON 序列化

ruby-on-rails - 在没有 accepts_nested_attributes_for 的情况下处理 Rails 中的嵌套 JSON

matrix - Rust 特征 : The bounds might not be implemented, 并且我实现的特征不存在

initialization - 与结构同名的函数

rust - 函数返回 serde 反序列化类型时如何修复生命周期错误?