簡體   English   中英

在標量值上使用字面樣式與 Jackson 進行 YAML 序列化

[英]Use literal style on scalar values for YAML serialization with Jackson

我正在使用Jackson將對象序列化為 YAML( jackson-dataformat-yaml庫)。

我想為標量值(例如以下示例中的“描述”)生成文字樣式輸出,例如

---
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);

我想有一些可能會生成文字樣式標量值,但我不知道如何。 歡迎任何提示!

如果您自己使用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;
    }
}

我知道這是一年前的帖子,但這是 Google 建議的頂級鏈接,需要更新。

自 v.2.9 以來,Jackson 支持文字樣式。 盡管在此錯誤中尾隨空格存在問題

例子:

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));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM