使用 Jackson 格式化 YAML

Formatting YAML with Jackson

我正在使用 Jackson 库将 Java 对象转换为 YAML 格式。根据我在 Internet 上找到的文档,我能够快速编写一个执行转换的函数。

我正在寻求将以下 classes 转换为 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"

我在 Internet 上看到的所有示例都使用 Employee class,并讨论如何将 class 转换为 YAML,但没有说明如何避免“-- -”(或将其更改为更具描述性的内容)。我也找不到任何说明如何按照我描述的方式对 YAML 进行分组的内容。

有人知道怎么做吗?有没有办法消除“---”,或创建一个名称(如 "RequestInfo")将翻译后的数据分组到一个对象中?

您可以通过禁用 YAMLGenerator.Feature.WRITE_DOC_START_MARKER 来忽略 ---.. 如果您想将值包装在 class 名称下,那么您需要使用 @JsonRootName...

试试这个:

RequestInof class:

@JsonRootName("RequestInfo")
public class RequestInfo
{
   private String thePath;
   private String theMethod;
   private String theURL;

   private List<ParamInfo> theParams = new ArrayList<>();

   // getters and setters
}

测试:

public String basicTest()
{
        ObjectMapper theMapper = new ObjectMapper(new YAMLFactory().disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER));
        theMapper.enable(SerializationFeature.WRAP_ROOT_VALUE);   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);
}