将TOML反序列化为带有值的枚举向量 [英] Deserializing TOML into vector of enum with values
问题描述
我正在尝试读取TOML文件以创建一个结构,该结构包含带有相关值的枚举向量.这是示例代码:
I'm trying to read a TOML file to create a struct that contains a vector of enums with associated values. Here's the sample code:
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate toml;
use std::fs::File;
use std::io::Read;
#[derive(Debug, Deserialize, PartialEq)]
struct Actor {
name: String,
actions: Vec<Actions>,
}
#[derive(Debug, Deserialize, PartialEq)]
enum Actions {
Wait(usize),
Move { x: usize, y: usize },
}
fn main() {
let input_file = "./sample_actor.toml";
let mut file = File::open(input_file).unwrap();
let mut file_content = String::new();
let _bytes_read = file.read_to_string(&mut file_content).unwrap();
let actor: Actor = toml::from_str(&file_content).unwrap();
println!("Read actor {:?}", actor);
}
Cargo.toml
[dependencies]
serde_derive = "1.0.10"
serde = "1.0.10"
toml = "0.4.2"
sample_actor.toml
name = "actor1"
actions = [move 3 4, wait 20, move 5 6]
我知道文件看起来错误",但是我不知道如何在TOML文件中编写动作,以便板条箱能够将它们识别为具有X个值的枚举.
I know the file looks "wrong", but I have no idea how I should write the actions in the TOML file such that the crate would be able to recognize them as an enum with X number of values.
使用cargo run
运行此示例时遇到的错误如下:
The error I get when running this example with cargo run
is the following:
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Error { inner: ErrorInner { kind: NumberInvalid, line: Some(1), col: 11, message: "", key: [] } }', /checkout/src/libcore/result.rs:906:4
note: Run with `RUST_BACKTRACE=1` for a backtrace.
我知道我可能需要为枚举实现FromStr
以便将字符串转换为枚举,并且我简短地知道可以实现自定义反序列化器以特定方式反序列化,但是我不确定这些块放在一起.
I know that I probably need to implement FromStr
for my enum to convert a string into my enum, and I briefly know that custom deserializers can be implemented to deserialize in a specific way, but I'm not sure how these pieces fit together.
似乎使用serde_json代替TOML的等效示例可以直接工作(当然,使用JSON文件代替TOML).
It seems an equivalent example using serde_json instead of TOML works straight out (using JSON files instead of TOML of course).
代码的JSON版本:
extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
use serde_json::Error;
use std::fs::File;
use std::io::Read;
#[derive(Debug, Serialize, Deserialize)]
enum Foo {
bar(u32),
baz { x: u32, y: u32 },
}
#[derive(Debug, Serialize, Deserialize)]
struct Address {
street: String,
city: String,
nums: Vec<Foo>,
}
fn main() {
/*
let address = Address {
street: "10 Downing Street".to_owned(),
city: "London".to_owned(),
nums : vec![Foo::bar(1), Foo::baz{x : 2, y : 3}],
};
// Serialize it to a JSON string.
let j = serde_json::to_string(&address).unwrap();
// Print, write to a file, or send to an HTTP server.
println!("{}", j);
*/
let input_file = "./sample_address.json";
let mut file = File::open(input_file).unwrap();
let mut file_content = String::new();
let _bytes_read = file.read_to_string(&mut file_content).unwrap();
let address: Address = serde_json::from_str(&file_content).unwrap();
println!("{:?}", address);
}
在此示例中读取/写入的JSON数据为:
The JSON data read/written in this example is:
Address { street: "10 Downing Street", city: "London", nums: [bar(1), baz { x: 2, y: 3 }] }
也许TOML板条箱不能支持我的用例?
Maybe the TOML crate can't support my use-case?
推荐答案
Serde具有许多用于序列化的选项枚举.
适合您的情况的
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate toml;
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(tag = "type", content = "args")]
enum Actions {
Wait(usize),
Move { x: usize, y: usize },
}
fn main() {
println!("{}", toml::to_string(&Actions::Wait(5)).unwrap());
println!("{}", toml::to_string(&Actions::Move { x: 1, y: 1 }).unwrap());
}
type = "Wait"
args = 5
type = "Move"
[args]
x = 1
y = 1
这篇关于将TOML反序列化为带有值的枚举向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!