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: