How to use Serde to parse a YAML file with multiple different types? [duplicate]

非 Y 不嫁゛ 提交于 2019-12-13 15:17:25

问题


I'm trying to parse this YAML file

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

I've created this code that works perfectly:

#[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);
        }
    }
}

I need to support this format too:

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

How I can deal with two different ways to parse?

来源:https://stackoverflow.com/questions/55245914/how-to-use-serde-to-parse-a-yaml-file-with-multiple-different-types

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!