json - 反序列化不规则内容的JSON

标签 json rust

我有下面的示例,其中可能会发生 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/

相关文章:

rust - rust-chrono 中的 ParseError(NotEnough) 是什么意思?

ajax - 结果显示为空

json - 关于ElasticSearch过滤器聚合的需求说明

linux - Rust 1k TCP 连接限制

string - 如何从整数转换为字符串?

rust - 如何将具体值移出 Box<dyn Any>?

Java 解码 JSON

javascript - 在两个日期之间搜索 JSON

java - 如何在 blogger api 中按标签获取博客文章

generics - Rust:对通用参数的引用不满足特征绑定(bind)