Reputation: 307
I am writing a wordle game and need to parse and edit json file. I follow Docs but get errors.
This is my json file:
{
"total_rounds": 6,
"games": [
{
"answer": "POSER",
"guesses": [
"HELLO",
"CRANE",
"POWER",
"POKER",
"POSER"
]
}
}
My code is rewritten from serde_json docs.
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;
}
There are four similar errors.
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;
| ^^^^^^^^^^^^^^^^
Cargo.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"
I don't know why I get errors as I follow docs.
Upvotes: 0
Views: 1099
Reputation: 2214
Rust comes with a elegant native-json crate, which declares JSON object natively.
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);
}
Upvotes: 0
Reputation: 70910
You need to enable the derive
feature of serde
:
serde = { version = "1.0.144", features = ["derive"] }
Upvotes: 1