Jackson Yaml库无法解析有效的Yaml文件

时间:2018-07-27 07:24:37

标签: java jackson yaml jackson2 jackson-databind

我正在使用杰克逊yaml解析器jackson-dataformat-yaml来解析YAML文件,但无法解析以下YAML文件。

environments:
  linux:
    - [rbenv,python-2.7]

env:
  global:
    # The username below should have write access to your module repository, to automatically commit new version tags.
    - USERNAME=sdfasfaf
    - secure: "fadfasdf" 

build: |
  set -o errexit
  set -o nounset

  #./bootstrap_factory_utils

解析- USERNAME=sdfasfaf属性时遇到问题。以下是代表YAML文件的pojo类。

SFYaml.java:

public class SFYaml {

    private Environments environments;

    private Env env;

    private String build;

}

Env.java:

public class Env {

    private Global[] global;

}

Global.java:

public class Global {

    private String secure;

}

解析yaml文件的方法:

public String readYaml() {
        YAMLFactory yamlFactory = new YAMLFactory();
        YAMLMapper yMapper = new YAMLMapper(yamlFactory);
        yMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        String output = "";
        try {
            SFYaml sfYaml = yMapper.readValue(new File(yamlPath), SFYaml.class);
            output = yMapper.writeValueAsString(sfYaml);
            log.info(sfYaml.getPublish());
            // log.info(output);
        } catch (JsonProcessingException e1) {
            e1.printStackTrace();
        } catch (IOException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        }
        return output;
    }

我尝试添加@JsonProperty批注@JsonIgnoreProperties(ignoreUnknown = true),并尝试了各种DeserializationFeature功能来禁用解析失败,但是我总是遇到以下错误。

  

com.fasterxml.jackson.databind.exc.MismatchedInputException:无法   构造com.amadeus.bitbucket.pojos.Global的实例(尽管   至少存在一个创建者):没有字符串参数构造函数/工厂   从字符串值('USERNAME = sdfasfaf')反序列化的方法   [源文件);行:12,列:7](通过参考链:   com.amadeus.bitbucket.pojos.SFYaml [“ env”]-> com.amadeus.bitbucket.pojos.Env [“ global”]-> java.lang.Object [] [0])     在   com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:63)     在   com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1342)     在   com.fasterxml.jackson.databind.DeserializationContext.handleMissingInstantiator(DeserializationContext.java:1031)     在   com.fasterxml.jackson.databind.deser.ValueInstantiator._createFromStringFallbacks(ValueInstantiator.java:371)     在   com.fasterxml.jackson.databind.deser.std.StdValueInstantiator.createFromString(StdValueInstantiator.java:323)

如何解析此USERNAME=sdfasfaf属性?还是使用任何变通办法?

0 个答案:

没有答案