Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print Jersey JSON in Unit Testing

Tags:

json

jaxb

jersey

Is there any plain way

  • 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?

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

Is there any example for JSON?


I found it. It's similar to JAXB.

With 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>
like image 613
Jin Kwon Avatar asked May 15 '12 02:05

Jin Kwon


1 Answers

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.

like image 182
logoff Avatar answered Nov 01 '22 09:11

logoff