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

2023-11-21

我想序列化为 Jsonorg.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());

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


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

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

正在建设一个outbound回复。在 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。

  • 阅读更多关于实体提供商

话虽这么说,泽西岛有一个测试框架,我们可以用来测试我们的资源方法。你可以找到所有官方示例在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提供了MessageBodyWriter and MessageBodyReader用于处理 JSON,它是为我们隐式注册的。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 javax.ws.rs 实体序列化为 json 的相关文章

随机推荐