我有下面的示例,其中可能会发生 2 种“不寻常”的事情:
- 如果状态为
NOK
,则根本不会包含data
元素 list
中元素的某些属性可能丢失(在下面的示例中,list
的第二个元素中缺少key2
。
有没有办法使用自动推导对不规则的 JSON 字符串进行反序列化?
在 Rust 中处理这种不规则 JSON 的最简单/更好的方法是什么?我能否避免编写非常复杂的基于匹配
的代码来检查所有可能的组合?
extern crate serialize;
static JSON: &'static str = r#"
{
"status": {
"status": "OK"
},
"data": {
"container": {
"key": "value",
"list": [
{
"key1": "value1",
"key2": "value2"
},
{
"key1": "value1"
}
]
}
}
}"#;
#[deriving(Decodable, Show)]
struct Top {
status: Status,
data: Data,
}
#[deriving(Decodable, Show)]
struct Data {
container: Container,
}
#[deriving(Decodable, Show)]
struct Status {
status: String,
}
#[deriving(Decodable, Show)]
struct Container {
key: String,
list: Vec<KeyVals>,
}
#[deriving(Decodable, Show)]
struct KeyVals {
key1: String,
key2: String,
}
fn main() {
let result: Top = match serialize::json::decode(JSON) {
Ok(x) => x,
Err(why) => fail!("Failed decoding the JSON! Reason: {}", why),
};
println!("{}", result);
}
运行代码时失败,因为列表的第二个元素缺少 key2
属性。
task '<main>' failed at 'Failed decoding the JSON! Reason: MissingFieldError(key2)', hello.rs:56
谢谢
最佳答案
可能存在的数据可以通过枚举来表示。在最简单的情况下,使用 Option
。
我相信使用枚举也能解决您的问题。
#[deriving(Encodable, Decodable)]
enum Status {
Good(Container),
Bad,
VeryBad
}
如果容器还包含可能存在的数据,那么您可以再次使用枚举来表示它。
关于json - 反序列化不规则内容的JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25471637/