1

I am new to JAX-RS, I am trying to learn new things about it. I am stuck with one issue regarding, creating a JSON object in Java Script, posting it through ajax to a Java class using JAX-RS and annotations and creating a JSON file out of it. I am creating a Maven project for it. Can anyone please suggest me any tutorial for this. I am trying to implement it from past 1 week but unable to do anything.

Any suggestions appreciated. My POST annotation in Java is:

@POST
@Path("/post")
@Consumes(MediaType.APPLICATION_JSON) 
@Produces(MediaType.APPLICATION_JSON)
public void post(Message obj){
System.out.println("in post");
String v_id = obj.getID();
String v_email = obj.getEmail();
String v_checkedornot =  obj.getCheckedOrNot();
System.out.println("id " + v_id +" email " + v_email + " checkedornot " + v_checkedornot);
}

And my AJAX POST is:

var passingObject = {
        ID : '123456',
        userEmail : 'a.a@a',
        ApproverFlag : 'true'
    }

var passobj = JSON.stringify(passingObject);
    $.ajax({
    url: './webapi/messages/post',
    type: 'POST',
    contentType:"application/json",
    data: passobj,
    dataType:'json',
    success:function(data){
        alert(JSON.stringify(data));
    }
},'json');
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
tpsaitwal
  • 422
  • 1
  • 5
  • 23

2 Answers2

2

Just map the Javascript objects to Java objects. Here is basic mapping. It's pretty simple.

Javascript Object maps to Java object (or POJO)

var obj = {};

public class MyObject {}

Javascript properties map to Java fields/properties

var obj = {
    firstName: "Tejas",
    lastName: "Saitwal"
}

public class MyObject {
    private String firstName;
    private String lastName;
    // getters-setters
}

Javascript arrays map to Java List or Java array.

var obj = {
    firstName: "Tejas",
    lastName: "Saitwal",
    hobbies: ["dancing", "singing"]
}

public class MyObject {
    private String firstName;
    private String lastName;
    private List<String> hobbies;
    // getters-setters
}

Javascript nested objects map to Java nested objects

var obj = {
    firstName: "Tejas",
    lastName: "Saitwal",
    hobbies: ["dancing", "singing"],
    address: {
        street: "1234 main st",
        city: "NYC"
    }
}

public class MyObject {
    private String firstName;
    private String lastName;
    private List<String> hobbies;
    private Address address;
    // getters-setters
}
public class Address {
    private String street;
    private String city;
}

Javascript lists of objects map to Java List<Type> or Type[]

var obj = {
    firstName: "Tejas",
    lastName: "Saitwal",
    hobbies: ["dancing", "singing"],
    address: {
        street: "1234 main st",
        city: "NYC"
    },
    friends: [
        { name: "friend1", phone: "123456578" },
        { name: "friend2", phone: "123454567" }
    ]
}

public class MyObject {
    private String firstName;
    private String lastName;
    private List<String> hobbies;
    private Address address;
    private List<Friend> friends;
    // getters-setters
}
public class Address {
    private String street;
    private String city;
}
public class Friend {
    private String name;        
    private String phone;
}

Now you have a Java class (MyObject) that maps cleanly with the Javascript object. So you can have MyObject as a method parameter.

@POST
@Consumes("application/json")
public Response post(MyObject obj) {}

$.ajax({
    url: url,
    contentType: "application/json",
    data: JSON.stringify(obj)
});

That's not all. You need a provider (or MessageBodyReader) that knows how to deserialize the JSON into your POJO. For that Jackson is my preferred way to go. Just add this Maven dependency

<dependency>
    <groupId>com.fasterxml.jackson.jaxrs</groupId>
    <artifactId>jackson-jaxrs-json-provider</artifactId>
    <version>2.6.0</version>
</dependency>

Then you need to register the JacksonJsonProvider with your application. There are a bunch of ways this can be done, but without know the JAX-RS implementation and version you are using, I would have to list all the different ways. So if you are unsure about how to register it, please let me know the JAX-RS implementation you are using, the version of the implementation, and show how you are currently configuring your application (i.e. web.xml or Java config).

See Also:

Community
  • 1
  • 1
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
  • 1
    Thank you so much for your help. Could you please guide me on how to accept the `JSON` object in my `Java` class.@peeskillet. – tpsaitwal Sep 14 '15 at 12:23
  • 1
    What do you mean accept? You don't need to do anything. Jackson deserializes the JSON into `MyObject` and hands it off the JAX-RS, then JAX-RS hands it off to your method as the argument. You don't need to do anything else. – Paul Samsotha Sep 14 '15 at 12:25
  • Can you please just elaborate upon the URL. Means how should it be?@peeskillet – tpsaitwal Sep 15 '15 at 04:04
  • Do you have any experience using jQuery? This is basic jQuery AJAX code. If not, then let me know how you were currently trying to make AJAX requests. You need to have _some_ knowledge of using Javacript. No one here will give you a complete tutorial, and even _asking_ for a tutorial is off-topic here. jQuery is the easiest Javacript framework to use. I would suggest picking up a tutorial on jQuery, at least lookup how to make AJAX request with jQuery. The url is nothing more than the request url. But this will mean nothing to you if you don't at least have a little idea of how jQuery works – Paul Samsotha Sep 15 '15 at 04:08
  • See my edit. My `print` statement in `Java` is giving me `null` for all three variables and the `ajax` `success:` is retirning me `undefined`. @peeskillet – tpsaitwal Sep 15 '15 at 07:46
  • 1
    For the Javascript, use lowercase letters (camel case for multiple words). And in the Java POJO make sure the getters and setters are following Java naming convention, i.e. `String id;` -> `public String getId(), pubic void setId(String id)`. For the undefined, you aren't returning anything what do you expect. If you want to test it, just return the same `Message` instead of `void` – Paul Samsotha Sep 15 '15 at 07:50
  • 1
    They should also match your Javacript. For example you have `userEmail` but the Java property is just `getEmail()`, it should be `getUserEmail()` and `setUserEmail(String email) { this.userEmail = email; }` – Paul Samsotha Sep 15 '15 at 07:54
  • 2
    Thanks@peeskillet. Everything you told worked for me. – tpsaitwal Sep 15 '15 at 09:50
  • can you please look into it. [link](http://stackoverflow.com/questions/33735610/how-to-get-a-single-value-response-from-java-in-an-ajax-success-function) – tpsaitwal Nov 17 '15 at 06:13
-1

You have to set the contentType as JSON and in the service side you need to annotate method like below

@Produces(MediaType.APPLICATION_JSON) // produces JSON object as response
@Consumes(MediaType.APPLICATION_JSON)
Stefan Ferstl
  • 5,135
  • 3
  • 33
  • 41
Ram
  • 55
  • 5