consume json in jax-rs

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

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

 

 

Share Button

Prasad Kharkar

Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

3 thoughts on “consume json in jax-rs

  • July 26, 2016 at 12:17 pm
    Permalink

    I tried this example but I don’t know where I type {“name”:”prasad”, “surname”:”kharkar”}.

    I typed chrome Advanced Rest Client’s Raw Headers section by using application/json. Am I wrong here ?

    Thanks your help

    Reply
    • July 26, 2016 at 2:01 pm
      Permalink

      Hi Talha, there is payload field in advanced rest client under headers section. You need to provide data in it.

      Reply
  • April 26, 2017 at 2:52 pm
    Permalink

    PLs, do not forget to add:
    Content-Tpe: application/json

    in the Favorite Headers of the Chrome rest Client page

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *