1

I am trying to read json payload in restful webservice in java. But I am not sure how to do. I researched a lot but was not able to find something useful. can some one help me.

JQUERY:

$(function () {
    var arr = {"name":"susheel", "rollNo:" :"123423"};
    $.ajax({
        url: 'http://localhost:8080/restapi/test',
        type: 'POST',
        data: JSON.stringify(arr),
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        async: false,
        success: function (msg) {
            alert(msg);
        }
    });
});

Restful webservice code:

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/test")
public class ProjectInfo {      
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public String submitProject(String s) {        
        return s;
    }
}

check the screenshot

Susheel Singh
  • 3,824
  • 5
  • 31
  • 66
  • Maybe try getting rid of the @Consumes line also what problem are you having? – brso05 Jan 20 '15 at 13:56
  • Which version of JQuery are you using? – Stephan Jan 20 '15 at 13:56
  • What error are you getting? – brso05 Jan 20 '15 at 13:57
  • POST http://localhost:8080/restapi/test 405 (OK) – Susheel Singh Jan 20 '15 at 13:58
  • My doubt is how do I receive the payload value in the webservice – Susheel Singh Jan 20 '15 at 14:00
  • @susheel you need to add annotation to tell it what it is like `@FormParam()` or `@QueryParam` – brso05 Jan 20 '15 at 14:03
  • @susheel you do know that it will automatically generate the JSON for you...you just need to return a student object: `public Student submitProject(Student s) {` `return new Student();` It will take a `Student` object and create the JSON for that object. I think you need a default (empty) constructor (you can have more than 1) also getters and setters for your variables and `@XmlRootElement()` notation right before your class declaration. These things go in the Student class. – brso05 Jan 20 '15 at 14:11

4 Answers4

2

You need to add annotation like this:

public String submitProject(@FormParam("mydata") String test) {

If you were doing a get request and attaching to url you would use:

@QueryParam("mydata") String test

You probably want something like:

data: {mydata : JSON.stringify(arr)}

UPDATE*************************************************************************

$(function () {
    var arr = {"name":"susheel", "rollNo:" :"123423"};
    $.ajax({
        url: 'http://localhost:8080/restapi/test',
        type: 'POST',
        data: {name : "susheel", rollno : "123423"},
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        async: false,
        success: function (msg) {
            alert(msg);
        }
    });
});

@XmlRootElement()
public class Student {
    private String name;
    private String rollNo;
    public Student()
    {
    }
    public Student(String name, String rollNo)
    {
        this.name = name;
        this.rollNo = rollNo;
    }
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getRollNo() {
        return rollNo;
    }

    public void setRollNo(String rollNo) {
        this.rollNo = rollNo;
    }
}


import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/test")
public class ProjectInfo {      
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    public Student submitProject(@FormParam("name") String name, @FormParam("rollno") String rollNo) {
        Student student = new Student(name, rollNo);      
        return student;
    }
}
brso05
  • 13,142
  • 2
  • 21
  • 40
  • 1
    there is no name. its a request payload. – Susheel Singh Jan 20 '15 at 14:03
  • @susheel you should give it a name you are passing it as `data` so you should give it a name. – brso05 Jan 20 '15 at 14:03
  • @susheel I don't know how to access the payload but if you give it a name then you can pass it like I show above in my answer...try it if you want to. – brso05 Jan 20 '15 at 14:09
  • It works if I give the name thanks. But I want to find if name is not given to the payload. – Susheel Singh Jan 20 '15 at 14:17
  • @susheel I updated my answer as to how I would do it. Please take a look maybe try it and see if it works for you. – brso05 Jan 20 '15 at 14:22
  • @susheel `msg` returned will actually be a javascript object so you can access like `msg.name` or `msg.rollNo` `alert("" + msg.name);` `alert("" + msg.rollNo);` – brso05 Jan 20 '15 at 14:23
  • sorry that is not what I need my json request might be complex. like `{"name":{ "firstname":"susheel","lastname":"singh"}}` – Susheel Singh Jan 20 '15 at 14:24
  • @susheel that's not very complex I would use the way I showed you but if you insist on doing it the other way this link might help you http://www.javacodegeeks.com/2013/07/restful-webservices-with-jersey.html. You can pass parameter from javascript variable instead of hard coding... – brso05 Jan 20 '15 at 14:27
  • @susheel also you could pass the whole json string like I showed you then use java to create an object from the passed json string... – brso05 Jan 20 '15 at 14:30
  • let me think and get back to you.. thanks for your help. I upvoted your answer. – Susheel Singh Jan 20 '15 at 14:30
  • @susheel thats awesome! I'm glad you figured it out! – brso05 Jan 21 '15 at 13:22
1

You need to return a response object like so:

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/test")
public class ProjectInfo {      
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response submitProject(Student s) {        
        return Response.status(Response.Status.OK).entity(s).build();
    }
}

You do not really need to provide a toString that returns a json representation. Your jax-rs implementation will know how to serialize your object into json.

Also, if the body of the post does not contain anything else but the json representation of the object, then you do not need to provide a @FormDataParam annotation in the argument list.

This assuming that you have configured your application to use a jax-rs implementation like jersey with the correct servlet configuration etc.

The following link might help for application set up: How to set up JAX-RS Application using annotations only (no web.xml)?

Community
  • 1
  • 1
aifa
  • 524
  • 5
  • 6
0

there is a really easy to use json library from ceadarsoft, that might help you. It translates Json objects to Java objects without the need for annotations on your model.

The maven dependency is:

<dependency>
    <groupId>com.cedarsoftware</groupId>
    <artifactId>json-io</artifactId>
    <version>2.7.1</version>
</dependency>
systemkern
  • 1,302
  • 11
  • 13
0

This is how it worked for me the way I wanted.

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.codehaus.jettison.json.JSONObject;

@Path("/test")
public class ProjectInfo {      
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public String submitProject(JSONObject obj) {  
        //read the json object data and insert the content to DB.
        //generate the response you like and return it
        //ObjectMapper class from codehaus can be used to generated desired json response.
        return generatedJSONResponse;
    }
}

Thanks everybody for your inputs which helped me solve my problem.

Susheel Singh
  • 3,824
  • 5
  • 31
  • 66