在没有 Spring 的情况下解析 JAX RS 中的数组序列化

Resolve array serialization in JAX RS without Spring

我需要为数据库创建一个简单的 REST 接口以进行数据迁移。 我所做的是使用 Netbeans 从数据库中生成 entity-类 和 beans,并编写一些简单的 REST 服务。 然后我 运行 研究了 Jettison 的序列化问题,其中只有一个元素的列表不会序列化为列表。

我找到了这个问题的解决方案,似乎都需要 Spring 重新定义序列化提供程序或重新配置 Jettison 的 "serializeAsArray" 和 "arrayKeys"。

有没有办法在不需要 Spring 框架的情况下使用 Jackson 或配置 Jettison?

这里是 REST 服务定义:

@Path("/reseller")
@Produces({"application/json;charset=utf-8"})
public class ResellerWS {

@EJB
private ResellerFacade reseller;

@Path("/{id}")
@GET
public Reseller get(@PathParam("id") long id)
{
    ResellerReseller result = reseller.find(id);
    return result;
}

这是重要实体的一部分。 resellerdepartmentList 未序列化为具有一个条目的列表,而仅序列化为条目本身:

@OneToMany(mappedBy = "resellerId", fetch = FetchType.EAGER)
private List<Resellerdepartment> resellerdepartmentList;

...

public List<Resellerdepartment> getResellerdepartmentList() {
    return resellerdepartmentList;
}

服务 运行 在 TomEE Plus 1.7.4

Is there a way to either use Jackson or configure Jettison without the need for the Spring framework?

我强烈建议您使用 Jackson 而不是 Jettison,它不需要 Spring 配置。


要将 Jackson 用作 JAX-RS 的 JSON 提供程序,请在您的项目依赖项中添加 jackson-jaxrs-json-provider 工件:

<dependency>
    <groupId>com.fasterxml.jackson.jaxrs</groupId>
    <artifactId>jackson-jaxrs-json-provider</artifactId>
    <version>2.9.5</version>
</dependency>

此模块包含将 JSON 内容与 Java 对象绑定所需的 JacksonJsonProvider class, which is the basic implementation of JAX-RS abstractions (MessageBodyReader and MessageBodyWriter)。

配置ObjectMapper in JAX-RS, you can create a ContextResolver implementation. It will be picked up by the JacksonJsonProvider:

@Provider
public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {

    private final ObjectMapper mapper;

    public ObjectMapperContextResolver() {
        this.mapper = createObjectMapper();
    }

    @Override
    public ObjectMapper getContext(Class<?> type) {
        return mapper;
    }

    private ObjectMapper createObjectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        // Configure as per your needs
        return mapper;
    }
}

@Provider annotation marks an implementation of an extension interface that should be discoverable by the JAX-RS runtime. Alternatively, you can register the providers in your class that extends Application.