问题
I am playing with Jersey hosted with Grizzly and want to be able to consume and produce JSON, however I am getting 500 from the server in get request and media type unsupported in POST my server code is
org.glassfish.jersey.server.ResourceConfig rc = new ResourceConfig();
rc.packages("RestServer.controllers");
final Map<String, Object> initParams = new HashMap<String, Object>();
initParams.put("com.sun.jersey.config.property.packages", "rest");
initParams.put("com.sun.jersey.api.json.POJOMappingFeature", "true");
rc.addProperties(initParams);
webServer = GrizzlyHttpServerFactory.createHttpServer(uri, rc, false);
my POJO is:
@XmlRootElement
public class Dummy {
private int id;
private String name;
public Dummy(int id, String name) {
this.id = id;
this.name = name;
}
@XmlElement(name="id")
public int getId() {
return id;
}
@XmlElement(name = "name")
public String getName() {
return name;
}
}
and controller
@Path("/Dummies")
public class DummyController {
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response get() {
System.out.println("Get");
return Response.status(Status.OK)
.entity(new Dummy(-1, "hello"))
.build();
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response AddDummy(Dummy dummy) {
return Response.status(Status.CREATED).entity(dummy).build();
}
}
回答1:
You're using Jersey 2. In Jersey 2, there is no com.sun.jersey.api.json.POJOMappingFeature
and com.sun.jersey.config.property.packages
, so you can get rid of those.
To enable JSON to/from POJO, we need a MessageBodyWriter/MessageBodyReader
(see more here). Fortunately, we don't need to write these ourselves. You just need a dependency (see here).
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>${jersey2.version}</version>
</dependency>
This depedency will pull in the required Jackson MessageBodyReader/MessageBodyWriter
. Then just configure it
resourceConfig.register(JacksonFeature.class);
来源:https://stackoverflow.com/questions/28462830/enabling-json-using-jersey-and-grizzly