consume json in jax-rs

Hi, In previous article we have seen how we can create a simple hello world jax-rs web service. This article will explain how to consume json in jax-rs.

Consume Json in JAX-RS:

JAX-RS can be used to accept POST requests through which we can pass data. A common format for data interchange is json format. We can write web services to consume json in jax-rs. Javadoc provides a way to create a web service that accepts something using @Consumes annotation. Going forward with the hello world jax-rs example, we will write a service to consume json in jax-rs.

HelloWorldApplication.java

This gives the application the capability to use jax-rs web services under application path as “/rest”.

HelloWorldService.java

Points to note here,

  • @POST means the method accepts POST requests.
  • @Path means the method will be invoked when path is /rest/HelloWorld/writePersonToDB
  • @Consumes(MediaType.APPLICATION_JSON) tells that method accepts json objects and can convert into corresponding java object.

Person.java

This is a model class for which json representation we will be passing to writePersonToDB() method.

We are done with code to consume json in jax-rs. Let us try it out. Deploy the web app in jboss server and open chrome rest client. and send request as below.

URL: http://localhost:8080/JAX-RS_examples/rest/HelloWorld/writePersonToDB

json body: {“name”:”prasad”, “surname”:”kharkar”}

when you hit send, then writePersonToDB method will get called and it will print person object.

12:16:45,829 INFO [stdout] (default task-2) Person [name=prasad, surname=kharkar, address=null]

I hope this article helped understand how to consume json in jax-rs