在单元测试中打印Jersey JSON

时间:2022-10-24 19:38:24

Is there any plain way

有没有简单的方法

  • to print a JAXB annotated instance
  • 打印JAXB带注释的实例

  • in JSON format (as exactly jersey will print in AS)
  • 采用JSON格式(正如运动衫将在AS中打印)

  • while running unit testing
  • 在运行单元测试时

  • without any embedded server launched?
  • 没有启动任何嵌入式服务器

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

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

Is there any example for JSON?

JSON有什么例子吗?


I found it. It's similar to JAXB.

我找到了。它类似于JAXB。

With Jersey API

使用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

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

1 个解决方案

#1


2  

It is possible:

有可能的:

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

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

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

#1


2  

It is possible:

有可能的:

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

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

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