JAX-RS: How can I return my list of objects as JSON?

I looked at the Jackson documentation and it left me confused :( My object is as follows:

@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; } 

and my JAX-RS looks like

 @Path("/variable") public class VariableResource { @Inject private VariableManager variableManager; @GET @Produces(MediaType.APPLICATION_JSON) public Response getVariables() { return Response.ok(variableManager.getVariables()).build(); } } 

When I test this service with curl http://localhost:8080/app/rest/variable , I see the following in the server logs

 [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 

What are the simplest ways I can return a list of variables as JSON?

+4
source share
1 answer

This is usually as simple as adding @XmlRootElement to your Entity (I see that you are using JPA / Hibernate @Entity / @Table , but you are missing @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; } 

And this is for the service, using Response from JAX-RS, as well as directly returning an object that will be automatically marshaled by 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 created DTOs to avoid revealing the internal values โ€‹โ€‹of Entity from the database in the real world, but this is not necessary if you are good at exposing the whole object.

+12
source

All Articles