【问题标题】:Json parse and editJson解析和编辑
【发布时间】:2022-11-10 16:50:26
【问题描述】:

我正在写一个文字游戏,需要解析和编辑 json 文件。我关注Docs,但出现错误。

这是我的 json 文件:

{
  "total_rounds": 6,
  "games": [
    {
      "answer": "POSER",
      "guesses": [
        "HELLO",
        "CRANE",
        "POWER",
        "POKER",
        "POSER"
      ]
    }
}

我的代码是从 serde_json 文档重写的。

use std::{fs::File, io::BufReader};
use crate::Opt;
use serde::Deserialize;
use serde::Serialize;
use serde_json::Value;

#[derive(Serialize, Deserialize)]
pub struct State {
    total_rounds: i32,
    games: Vec<Game>,
}

#[derive(Serialize, Deserialize)]
pub struct Game {
    answer: String,
    guesses: Vec<String>,
}

pub fn get_json(opt: Opt) -> State {
    let file = File::open(opt.state.unwrap()).unwrap();
    let reader = BufReader::new(file);
    let state: State= serde_json::from_reader(reader).unwrap();
    return state;
}

有四个类似的错误。

error: cannot find derive macro `Serialize` in this scope
 --> src/json_parse.rs:8:10
  |
8 | #[derive(Serialize, Deserialize)]
  |          ^^^^^^^^^
  |
note: `Serialize` is imported here, but it is only a trait, without a derive macro
 --> src/json_parse.rs:5:5
  |
5 | use serde::Serialize;
  |     ^^^^^^^^^^^^^^^^

货运.toml

[dependencies]
atty = "0.2"
serde_json = "1.0.83"
console = "0.15"
rand = "0.8.5"
text_io = "0.1.12"
structopt = "0.3.26"
serde = "1.0.144"

我不知道为什么我在关注文档时会出错。

【问题讨论】:

  • 您的 Cargo.toml 中有什么?

标签: rust


【解决方案1】:

您需要启用serdederive 功能:

serde = { version = "1.0.144", features = ["derive"] }

【讨论】:

  • 谢谢你。我只需输入cargo add serde_json :(
【解决方案2】:

Rust 带有一个优雅的 native-json crate,它原生声明 JSON 对象。

use native_json::json;
use std::collections::HashMap;

fn main()
{
    let var = 123;
    let map = HashMap::from([ ("a", 1), ("b", 2), ("c", 3) ]);

    let mut t = json!{
        name: "native json",
        style: {
            color: "red",
            size: 12,
            bold: true
        },
        class: null,
        array: [5,4,3,2,1],
        vector: vec![1,2,3,4,5],
        hashmap: map,
        students: [
            {name: "John", age: 18},
            {name: "Jack", age: 21},
        ],
        rect: {x: 10, y: 10, width: 100, height: 50},
        sum: var + 10
    };

    // Native access
    t.rect.x += 10;
    t.rect.y += 20;

    // Debug
    println!("{:#?}", t);

    // Stringify
    let text = serde_json::to_string_pretty(&t).unwrap();
    println!("{}", text);

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-14
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-27
    相关资源
    最近更新 更多