【发布时间】:2020-04-29 16:09:28
【问题描述】:
我正在使用 Jackson 库将 Java 对象转换为 YAML 格式。根据我在 Internet 上找到的文档,我能够快速编写一个进行转换的函数。
我正在寻求将以下类转换为 YAML:
public class RequestInfo
{
private String thePath;
private String theMethod;
private String theURL;
private List<ParamInfo> theParams = new ArrayList<>();
// getters and setters
}
public class ParamInfo
{
private String paramName;
private String paramType;
// getters and setters
}
使用 Jackson 的 ObjectMapper,我可以轻松生成 YAML:
public String basicTest()
{
ObjectMapper theMapper = new ObjectMapper(new YAMLFactory());
RequestInfo info = new RequestInfo();
info.setThePath("/");
info.setTheMethod("GET");
info.setTheURL("http://localhost:8080/");
List<ParamInfo> params = new ArrayList<>();
params.add(new ParamInfo("resource","path"));
info.setTheParams(params);
String ret = null;
try
{
ret = theMapper.writeValueAsString(info);
}
catch(Exception exe)
{
logger.error(exe.getMessage());
}
return(ret);
}
我得到的 YAML 如下:
---
thePath: "/"
theMethod: "GET"
theURL: "http://localhost:8080/"
theParams:
- paramName: "resource"
paramType: "path"
我得到的 YAML 是可以的,但在我看来它有一些问题。一个问题是它开头的“---”。另一个事实是,我希望能够以类似于以下 YAML 的方式对信息进行分组:
RequestInfo:
thePath: "/"
theMethod: "GET"
theURL: "http://localhost:8080/"
theParams:
- paramName: "resource"
paramType: "path"
我在互联网上看到的所有示例都使用 Employee 类,并谈论如何将该类转换为 YAML,但没有说明如何避免“---”(或将其更改为更具描述性的)。我也找不到任何可以说明如何按照我描述的方式对 YAML 进行分组的内容。
有人知道怎么做吗?有没有办法消除“---”,或者创建一个名称(如“RequestInfo”)将已翻译的数据组合到一个对象中?
【问题讨论】:
标签: jackson yaml jackson-databind