Serialize javax.ws.rs Entity to json

I want to serizalize for Json with an implementation of org.glassfish.jersey

 Map<String, String> entity = Maps.newHashMap(); entity.put("foo", "bar"); Response response = Response.status(Response.Status.OK) .entity(entity) .type(MediaType.APPLICATION_JSON).build(); System.out.println(response.getEntity()); 

This map is converted to non-standard { foo: "bar" } . I want to test this behavior in unit test.

+6
source share
1 answer

You cannot verify this. What are you doing here?

 Response response = Response.status(Response.Status.OK) .entity(entity) .type(MediaType.APPLICATION_JSON).build(); 

creates an outgoing response. In the JAX-RS structure, after sending a response, for example,

 @GET @Produced(MediaType.APPLICATION_JSON) public Response getResponse() { ... return Response.status(Response.Status.OK) .entity(entity) .type(MediaType.APPLICATION_JSON).build(); } 

for serialization in JSON, you still need to execute MessageBodyWriter .

Considering that Jersey has a Test Framework , we can use resources to test our methods. You can find all official examples on Github.

Sample (with a few changes):

These are the minimum required Maven dependencies.

 <dependencies> <dependency> <groupId>org.glassfish.jersey.test-framework</groupId> <artifactId>jersey-test-framework-core</artifactId> <version>2.13</version> </dependency> <dependency> <groupId>org.glassfish.jersey.test-framework.providers</groupId> <artifactId>jersey-test-framework-provider-grizzly2</artifactId> <version>2.13</version> </dependency> <dependency> <groupId>org.glassfish.jersey.media</groupId> <artifactId>jersey-media-json-jackson</artifactId> <version>2.13</version> </dependency> </dependencies> 

Testing class

 public class TestJSONResource extends JerseyTest { @Override protected TestContainerFactory getTestContainerFactory() { return new GrizzlyTestContainerFactory(); } @Path("test") public static class TestResource { @GET @Produces(MediaType.APPLICATION_JSON) public Response getJson() { Map<String, String> entity = Maps.newHashMap(); entity.put("foo", "bar"); Response response = Response.status(Response.Status.OK) .entity(entity) .type(MediaType.APPLICATION_JSON).build(); return response; } } @Override protected DeploymentContext configureDeployment() { return DeploymentContext.builder(new ResourceConfig(TestResource.class)) .contextPath("context1/context2") .build(); } @Test public void testGet() { final WebTarget target = target("test"); final String s = target.request().get(String.class); System.out.println(s); } } 

jersey-media-json-jackson provides MessageBodyWriter and MessageBodyReader to handle JSON, which is implicitly registered for us.

+4
source

Source: https://habr.com/ru/post/978581/


All Articles