I am developing the REST application using Jersey and creating CRUD operations in my service.
My question is how to bind the JSON as an object in method. I am not able to doing the save operation using JSON request.
So please provide me any useful example which have developed the CRUD application.
Jersey JSON support comes as a set of extension modules such as MOXy and Jackson.
JSON binding support via MOXy is a default way of supporting JSON binding in your Jersey applications since Jersey 2.0. When JSON MOXy module is on the classpath, Jersey will automatically discover the module and enable JSON binding support via MOXy in your applications.
To use MOXy as your JSON provider you need to add jersey-media-moxy module to your pom.xml file:
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
<version>2.22.1</version>
</dependency>
If you're not using Maven make sure to have all needed dependencies on the classpath.
With MOXy, you can use JAXB annotations to control how the JSON is generated.
To use Jackson 2.x as your JSON provider you need to add jersey-media-json-jackson module to your pom.xml file:
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.22.1</version>
</dependency>
If you're not using Maven make sure to have all needed dependencies on the classpath.
Jackson 2.x provides a rich set of annotations to control how the JSON is generated from your POJOs.
Define a POJO which will be marshaled from/to JSON. Consider the following class as an example:
public class Book implements Serializable {
private Long id;
private String title;
private String description;
public Book {
}
// getters and setters ommited
}
Depending on your JSON provider, you can use annotate your POJO to control how the JSON is generated.
Create your REST endpoint. To consume data as JSON, simply annotate it with @Consumes(MediaType.APPLICATION_JSON). To produce JSON, annotate it with @Produces(MediaType.APPLICATION_JSON).
Consider the following class as an example to start:
@Path("/books")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class BookEndpoint {
@POST
public Response create(Book book) {
...
}
@GET
@Path("/id")
public Response read(@QueryParam("id") Long id) {
...
}
@PUT
@Path("/id")
public Response update(@QueryParam("id") Long id, Book book) {
...
}
@DELETE
@Path("/id")
public Response delete(@QueryParam("id") Long id) {
...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With