【问题标题】:Use literal style on scalar values for YAML serialization with Jackson使用 Jackson 对标量值进行 YAML 序列化的文字样式
【发布时间】:2018-03-13 14:33:48
【问题描述】:

我正在使用Jackson 将对象序列化为 YAML(jackson-dataformat-yaml 库)。

我想为标量值(例如以下示例中的“描述”)生成literal style 输出,例如

---
id: 4711
description: |
  FooBar
  HelloWorld

但我只能生成这样的带引号的标量:

---
id: 4711
description: "FooBar\nHelloWorld"

我用来生成 ObjectMapper 的代码(到目前为止)非常简单:

    YAMLFactory f = new YAMLFactory();
    f.enable(YAMLGenerator.Feature.SPLIT_LINES); // setting does not matter
    ObjectMapper objectMapperYaml = new ObjectMapper(f);
    String yaml = objectMapperYaml.writeValueAsString(someObject);

我猜有可能生成文字样式的标量值,但我不知道如何。欢迎任何提示!

【问题讨论】:

    标签: java jackson yaml


    【解决方案1】:

    如果您要单独使用 SNAKEYaml,则需要设置相应的转储器选项:

    DumperOptions dumperOptions = new DumperOptions();
    dumperOptions.setDefaultScalarStyle(ScalarStyle.LITERAL);
    

    很遗憾,这里无法通过 JacksonFeature 来完成。

    快速浏览源代码显示要启用的功能是MINIMIZE_QUOTES,您会在YAMLGenerator#writeString 中找到他们的算法。

    这是完整的课程:

    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
    import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator;
    
    public class NewClass {
    
        private int id;
    
        private String description;
    
        public static void main(String... a) throws JsonProcessingException {
            YAMLFactory f = new YAMLFactory();
            f.enable(YAMLGenerator.Feature.MINIMIZE_QUOTES);
            ObjectMapper objectMapperYaml = new ObjectMapper(f);
    
            final NewClass someObject = new NewClass();
            someObject.setId(4711);
            someObject.setDescription("Hallo\nWorld!");
            System.out.println(objectMapperYaml.writeValueAsString(someObject));
        }
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getDescription() {
            return description;
        }
    
        public void setDescription(String description) {
            this.description = description;
        }
    }
    

    【讨论】:

      【解决方案2】:

      我知道这是一年前的帖子,但这是 Google 建议的顶部链接,需要更新。

      Jackson 从 v.2.9 开始支持文字样式。尽管bug中的尾随空格存在问题@

      例子:

      YAMLMapper mapper = new YAMLMapper();
      mapper.configure(YAMLGenerator.Feature.LITERAL_BLOCK_STYLE, true);
      Map map = new HashMap();
      map.put("literal_ok", "some value\n wih\n   multiple\n    new lines\nin it");
      map.put("can_not_use_literal", "can not\n   use literal    \b because of the trailing spaces");
      System.out.println(mapper.writeValueAsString(map));
      

      【讨论】:

        猜你喜欢
        • 2019-03-17
        • 2022-12-10
        • 2021-12-13
        • 1970-01-01
        • 1970-01-01
        • 2014-05-28
        • 2011-07-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多