在单元测试中打印Jersey JSON

问题描述:

是否有任何简单的方法


  • 以JSON格式打印JAXB带注释的实例

  • (正如运动将在AS中打印)

  • 在运行单元测试时

  • 没有启动任何嵌入式服务器?

  • to print a JAXB annotated instance
  • in JSON format (as exactly jersey will print in AS)
  • while running unit testing
  • without any embedded server launched?

我可以使用JAXBContext,Marshaller等运行并查看XML。

I can run and see in XML with JAXBContext, Marshaller, and so on.

是否有任何示例JSON?

Is there any example for JSON?

我找到了它。它与JAXB类似。

I found it. It's similar to JAXB.

使用 Jersey API

final JSONJAXBContext context = new JSONJAXBContext(...);

final JSONMarshaller marshaller = context.createJSONMarshaller();
marshaller.marshallToJSON(...);

final JSONUnmarshaller unmarshaller = context.createJSONUnmarshaller();
final T unmarshalled = unmarshaller.unmarshalJAXBElementFromJSON(
        ..., T.class).getValue();






for Maven


for Maven

<dependency>
  <groupId>com.sun.jersey</groupId>
  <artifactId>jersey-json</artifactId>
  <scope>test</scope>
</dependency>


有可能:

...
StringWriter writer = new StringWriter();
marshaller.marshallToJSON(objectToMarshall, writer)
logger.debug(writer.toString());
...

您可以使用 StringWriter 获取编组的JSON输出的 String 表示。

You can use an StringWriter to take the String representation of the marshalled JSON output.