4

我查看了Jackson的文档,这让我很困惑 :( 我的实体看起来像:

 @Entity
 @Table(name = "variable")
 public class Variable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Column(unique = true, nullable = false)
    private String name;

    @Column
    @Enumerated(EnumType.STRING)
    private VariableType type;

    @Column(nullable = false)
    private String units;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "created_on", nullable = false)
    private Date createdOn;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "retired_on", nullable = true)
    private Date retiredOn;

    @Column(nullable = false)
    private boolean core;

}

我的JAX-RS服务看起来像

@Path("/variable")
public class VariableResource {
    @Inject private VariableManager variableManager;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response getVariables() {
        return Response.ok(variableManager.getVariables()).build();
    }

}

当我使用 测试此服务时curl http://localhost:8080/app/rest/variable,我在服务器日志中看到以下内容

[javax.ws.rs.core.Application]] (http--127.0.0.1-8080-6) Servlet.service() for servlet javax.ws.rs.core.Application threw exception: java.lang.NoSuchMethodError: org.codehaus.jackson.type.JavaType.<init>(Ljava/lang/Class;)V

有哪些最简单的方法可以将变量列表返回为 JSON?

4

1 回答 1

13

通常它就像@XmlRootElement在你的实体上添加一样简单(我可以看到你正在使用 JPA/Hibernate @Entity/ @Table,但你错过了@XmlRootElement)。

@Entity
@Table(name = "variable")
@XmlRootElement
public class Variable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Column(unique = true, nullable = false)
    private String name;

    // ...

    @Column(nullable = false)
    private boolean core;
}

这适用于服务,使用Response来自 JAX-RS,并且还直接返回将由 JAX-RS 自动编组的对象:

@Path("/variable")
public class VariableResource {
    @Inject private VariableManager variableManager;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response getVariables() {
        return Response.ok(variableManager.getVariables()).build();
    }

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    // Same method but without using the JAX-RS Response object
    public List<Variable> getVariablesAlso() {
        return variableManager.getVariables();
    }
}

Often people would create a DTO to avoid exposing internal values of the Entity from the database to the real world, but it is not mandatory, if it is fine for you to expose the whole object.

于 2013-01-14T20:39:46.790 回答