I am trying to consume JSON object sent by a client into a Map(or JSON object). I am using Jersey2.22.1 and by default it is using MOXY. Tried HashMap as shown below but no luck. It gives 415 error - "Unsupported Media Type"
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public List<Task> addTask(HashMap<String,Object> dynamicParam){
Tried with a custom class as well by wrapping a Map. again the same error. Can some one help me and let me know how to handle Map.
@XmlRootElement
public class DynamicFormData {
Map<Object,Object> data;
public Map<Object, Object> getData() {
return data;
}
public void setData(Map<Object, Object> data) {
this.data = data;
}
As a temp Solution, I am using below code. But would like to know how to correctly do this with Map
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public List<Task> addTask(String dynamicParam){
log.info("addTask Start");
Gson gson = new Gson();
Map<String, Object> map = new HashMap<String, Object>();
map = (Map<String, Object>)gson.fromJson(dynamicParam, map.getClass());
Use @Consumes({MediaType.APPLICATION_FORM_URLENCODED})
in combination with javax.ws.rs.core.MultivaluedMap
Working example:
JS-Client:
function postCalling(){
$.ajax({
type: 'POST',
url: "<url>",
contenttype: "application/json",
datatype: "json",
data: {
'paramOne': 'ONE',
'paramTwo' : 'TWO'
},
success: function (data, status, jqXHR) {
alert('It worked!: '+JSON.stringify(data));
},
error: function (jqXHR, status) {
alert('didnt work!');
}
});
Jersey-Code:
@POST
@Produces({MediaType.APPLICATION_JSON})
@Consumes({MediaType.APPLICATION_FORM_URLENCODED})
@Path("/sample")
public String getCumGa1Json(MultivaluedMap<String, String> postDataMap) {
System.out.println(postDataMap.get("paramOne").get(0));
//prints ONE
System.out.println(postDataMap.get("paramTwo").get(0));
//prints TWO
return toJSon(anObject);
}