I'm building a React app utilizing Rust for complex computations. In this case I'm passing a JSON formatted string from the React app to Rust:
{
{'clientid': 1, 'category': 'Category #1', 'subcategory': 'Subcategory #1', 'cost': 1000.00},
{'clientid': 1, 'category': 'Category #1', 'subcategory': 'Subcategory #2', 'cost': 2000.00}
}
I'm trying to figure out how to deserialze string In Rust into an array of structs defined as:
#[derive(Serialize, Deserialize, Debug)]
struct ClientBudget {
clientid: u32,
category: String,
subcategory: String,
cost: f32,
}
I tried:
let deserialized: ClientBudget = serde_json::from_str(&some_json).unwrap();
But this causes a panic:
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Error("key must be a string"
How do I get Rust/serde to process this JSON string?
Your JSON is badly formatted. If you want a list, you must use []
not {}
. You also need to deserialize a Vec
of objects:
use serde::{Deserialize, Serialize}; // 1.0.114
#[derive(Serialize, Deserialize, Debug)]
struct ClientBudget {
clientid: u32,
category: String,
subcategory: String,
cost: f32,
}
fn main() {
let data = r#"
[
{"clientid": 1, "category": "Category #1", "subcategory": "Subcategory #1", "cost": 1000.00},
{"clientid": 1, "category": "Category #1", "subcategory": "Subcategory #2", "cost": 2000.00}
]
"#;
let deserialized: Vec<ClientBudget> = serde_json::from_str(data).unwrap();
println!("{:?}", deserialized);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.