解析Yaml文件时出错-无法为JavaBean创建属性

时间:2019-01-28 19:44:43

标签: java jackson yaml snakeyaml

Yaml文件包含:

test:
  subHeading: "1234"

Model.java

class Model{
  @JsonProperty("test")
  private SubHeading subHead;

  private class SubHeading{
     @JsonProperty("subHeading")
      private String text;
  }

我尝试按以下方式解析上述Yaml内容:

Yaml yaml = new Yaml(new Constructor(Model.class));
System.out.println(yaml.load(new FileReader(PATH)).toString());

我立即得到一个例外:

Cannot create property=test for JavaBean=Model@13a5fe33
 in 'reader', line 1, column 1:
    test:

有什么主意我做错了什么,我可以在这里改变什么?

1 个答案:

答案 0 :(得分:0)

所有拳头都使用Jackson注释,但使用SnakeYaml库读取yaml文件。您必须通过以下方式简化解决方案:

  1. 简化模型
  2. 使用Jackson
  3. 在属性与注释中的值同名的情况下,删除Jackson注释。

模型
在新文件中将每个类创建为public class

public class Model {

    private SubHeading test;

    public SubHeading getTest() {
        return test;
    }

    public void setTest(SubHeading test) {
        this.test = test;
    }

    @Override
    public String toString() {
        return "Model{" +
                "test=" + test +
                '}';
    }
}

public class SubHeading {
    private String subHeading;

    public String getSubHeading() {
        return subHeading;
    }

    public void setSubHeading(String subHeading) {
        this.subHeading = subHeading;
    }

    @Override
    public String toString() {
        return "SubHeading{" +
                "subHeading='" + subHeading + '\'' +
                '}';
    }
}

用法示例:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;

public class YamlTest {

    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
        mapper.enable(SerializationFeature.INDENT_OUTPUT);

        String text = "test:\n" +
                "  subHeading: \"1234\"";

        Model model = mapper.readValue(text, Model.class);
        System.out.println(model);
    }
}

以上打印:

Model{test=SubHeading{subHeading='1234'}}