我想创建一个yaml文件,如下所示:
hello: World
value: 3
lists:['T1','T2']
我想出了以下代码:
public static void main(String[] args) throws IOException {
Data data = new Data();
data.setHello("World");
data.setValue(3);
data.setLists(Arrays.asList("T1","T2"));
ObjectMapper objectMapper =
new ObjectMapper(
new YAMLFactory()
.disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER)
.enable(YAMLGenerator.Feature.MINIMIZE_QUOTES)
);
objectMapper.writeValue(new File("filename.yaml"), data);
}
@Data
private static class Data {
private String hello;
private int value;
private List<String> lists;
}
但是这段代码返回的输出如下:
hello: World
value: 3
lists:
- T1
- T2
任何人都可以指导我如何使用 jackson 获取 Yaml 的单行数组格式吗?
我面临着同样的问题,终于能够实现我想要的 下面是可能有帮助的代码。
public static void main( String[] args )throws IOException
{
// Sample map with list value
Map<String, Object> data = new HashMap<>();
data.put("hello", "World");
data.put("value", 3);
List<String> list = new ArrayList<>();
list.add("T1");
list.add("T2");
data.put("lists", list);
// Create YAML object
Yaml yaml = new Yaml();
// Serialize map to YAML
String yamlString = yaml.dump(data);
// Replace single quotes around list values
yamlString = yamlString.replaceAll("'(\\[.*?\\])'", "$1");
// Write YAML to file
FileWriter writer = new FileWriter("output_test.yaml");
writer.write(yamlString);
writer.close();
System.out.println("YAML conversion completed successfully!");
}