Reputation: 3253
I am using jersey in Java. I want to get JSON data sent via a post request. However, I am not sure how to do this, despite my searching. I am able to receive JSON data at a path, yet I can't figure out how to parse it into java variables. I assume that I need to use jackson to do this. However, I don't understand how to pass the received JSON to jackson.
@Path("/register")
public class ResourceRegister
{
@POST
@Consumes(MediaType.APPLICATION_JSON)
public String RegisterUser(//not sure what to take in here to get the json )
{
//code to deal with the json
}
Upvotes: 1
Views: 1075
Reputation: 14558
You just need to place @JsonProperty annotation to your class properties and add that class to your Resource method as paramater.
You might need @JsonIgnoreProperties annotation as well if you are not deserializing everything inside the incoming json
See below:
@POST
@Consumes(MediaType.APPLICATION_JSON)
public String registerUser(MyUser myUser)
{
//code to deal with the json
}
public class MyUser{
@JsonProperty
private String name;
@JsonProperty
private String surname;
//getters & setters & constructors if you need
}
Upvotes: 1
Reputation: 4262
There are several ways of accepting the JSON and using it in back-end. 1. set POJO elements using JAXB APIs and use object of that POJO class to access passed parameters. this will be helpful while JSON size is large. Example: your service declaration would be as following
@Path("/register")
public class ResourceRegister
{
@POST
@Consumes(MediaType.APPLICATION_JSON)
public String RegisterUser(RegParams regParams)
{
//code to deal with the json
}
.....
}
and you will write a POJO like following
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
@JsonIgnoreProperties(ignoreUnknown=true)
@JsonWriteNullProperties(false)
public class RegParams implements Serializable {
@JsonProperty("userId")
private long userId;
@JsonProperty("userName")
private String userName;
..
..
}
retrive JSON as a string and use jersey APIs to work with the same. in this case you can declare your service as following
@Path("/register")
public class ResourceRegister
{
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public String RegisterUser(@FormParam("jsonObj")String jsonString)
{
//code to deal with the json
}
.....
}
and you can process that string by using jersey APIs like following
ObjectMapper om = new ObjectMapper();
JsonNode mainNode = om.readTree(jsonString);
//access fields
mainNode.get..(as per data passed, string, int etc)
for more referance you can refer this or this
Upvotes: 2