如何使用Serde解析具有多种不同类型的YAML文件?

时间:2019-03-19 16:36:28

标签: rust yaml serde

我正在尝试解析此YAML文件

application:
  build: something
  container_name: another_thing
  environment:
    - ONE_ENV=fake
    - SEC_ENV=something

我创建的这段代码很完美:

#[macro_use]
extern crate serde_derive;
extern crate serde_yaml;

use std::fs::File;
use std::io::Read;

#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Application {
    application: Data,
}

#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Data {
    build: String,
    container_name: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    environment: Option<Vec<String>>,
}

fn main() {
    let filename = "example.yml";
    match File::open(filename) {
        Ok(mut file) => {
            let mut content = String::new();
            file.read_to_string(&mut content).unwrap();

            let application_data: Application = serde_yaml::from_str(&content).unwrap();
            println!("{:?}", application_data.application.environment);
        }
        Err(error) => {
            println!("There is an error {}: {}", filename, error);
        }
    }
}

我也需要支持这种格式:

application:
  build: something
  container_name: another_thing
  environment:
    ONE_ENV: fake
    SEC_ENV: something

我该如何处理两种不同的解析方式?

0 个答案:

没有答案