将javax.ws.rs实体序列化为json

时间:2014-11-23 17:15:35

标签: java json jersey jax-rs jersey-2.0

我想通过org.glassfish.jersey实施

向Json推广
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());

此地图序列化为非标准{ foo: "bar" }。我想在单元测试中测试这种行为。

1 个答案:

答案 0 :(得分:6)

你不能这样测试。你在这做什么

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

正在构建出站响应。在JAX-RS框架中,在我们发出响应之后,例如

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

仍然需要通过MessageBodyWriter来序列化为JSON。

话虽如此,泽西岛有一个Test Framework,我们可以用来测试我们的资源方法。您可以找到所有官方示例at the Github

一个样本(有一些改动):

这些是Maven依赖项所需的最低要求

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

测试课

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提供了MessageBodyWriterMessageBodyReader来处理JSON,这是我们隐式注册的。