I am trying to send JSON array of string and perform some task on serverside.
Here is my JS:
var x = ["Salam","Saghol","11"]
$.ajax({
url: '../rest/group/addusers',
type: 'POST',
data: JSON.stringify(x),
contentType: 'application/json',
dataType: 'json',
async: false,
success: function(msg) {
alert(msg);
}
});
And my Java method:
#POST
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
#Path("/addusers")
public Response addUsersToGroup(List<String> users) {
System.out.println(users);
return Response.status(Response.Status.OK).entity("Salam").build();
}
When I send the request I get "415 (Unsupported Media Type)" error message.
Please help me just passing the array elements (Strings) to the method below.
Thanks in advance.
P.S. Here are my headers:
The problem here is that the "users" parameter can't be deserialized. While my idea might be clear, the logic is not correct enough programmatically.
Usually data from POST are extracted using query parameters (using "=","?","&" as separator). In my case I put the data directly to POST output stream. And getting all data in string representation is more logical.
So I changed the code into this:
#POST
#Produces(MediaType.TEXT_HTML)
#Consumes(MediaType.APPLICATION_JSON)
#Path("/addusers")
public Response addUsersToGroup(String users) throws IOException {
ObjectMapper mapper = new ObjectMapper();
List<String> l = mapper.readValue(users, List.class);
for (String s : l) {
System.out.println("Item: "+s);
}
return Response.status(Response.Status.OK).entity("Salam").build();
}
And problem is solved. Thanks for attention.
Related
I am trying to post a json using ajax to my spring mvc controller I am using code like this in my js file:
$('#regist').click(function () {
$.ajax({
url: 'user/regist',
contentType: "application/json; charset=utf-8",
type: 'post',
dataType: 'json',
success: function (data) {
var json = JSON.stringify(data);
alert(json);
},
fail: function (errMsg) {
alert(errMsg);
},
data: JSON.stringify({
'IDCard': '1234567890'
})
})
});
the signature of my controller function is like this:
#RequestMapping(value = "/regist", method = RequestMethod.POST)
#ResponseBody
public ResultJson regist(HttpSession session, #RequestBody RegistFormJson json)
the RegistFormJson goes like this:
public class RegistFormJson {
private String IDCard;
public String getIDCard() {
return IDCard;
}
public void setiDCard(String IDCard) {
this.IDCard = IDCard;
}
}
now when I send my request, and what I get from my controller using
logger.info(json.getIDCard);
is null.When I change my bean propertity to idCard and change my other code as well ,I can get the result successfully. Who can tell me why ? And If I want to use IDCard in my code, how can I get the result .Thanks
Spring comes with Jackson API which uses Standard Java Code Convention to map JSON properties to Java models.
Since IDCard is not in lower camel case, Jackson API is not able to map the JSON property.
To overcome this you need to specify a #JsonProperty("IDCard") annotation on a Java attribute in order to use IDCard for your JSON property.
Likewise, you can set the PropertyNamingStrategy on the ObjectMapper to overcome this issue.
What I am trying to do is initiate an ajax call from my frontend code by user interaction. This calls a Java Restful service that I have written. And this Java function calls another service.
I need that java service in the middle because I need to send the inputs to other service in the format of "MyModel".
The problem is, the AJAX call works but it cannot get the JSON object that I send. You see in the Java function below I create the "param1" : "asdasd" for the second time there. That's because it cannot get the JSON data from front-end. It should be dynamically created with the argument of sendInputs function.
By the way when I debug the value String input is like this: ""
Javascript AJAX call:
var paramData = {"param1" : "asdasd"};
$.ajax({
type : 'GET',
url : "/api/v2/proxy",
dataType : "json",
headers : {
"Service-End-Point" : "http://localhost:9000/service/myService/sendInputs"
},
statusCode : {
200 : function(data) {
}
},
contentType : "application/json",
data : JSON.stringify(paramData),
error : function(error) {
}
});
Java consume:
#GET
#Path("/sendInputs")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public String sendInputs(String input) {
String result = null;
//define the service endpoint to be added the default URL
String serviceEndpoint = "otherService/tool/runTool";
List<MyModel> modelParameterList = new ArrayList<MyModel>();
MyModel inputParameter = null;
inputParameter = new MyModel("param1", "asdasd");
modelParameterList.add(inputParameter);
//convert the Java Map to a json string using Jackson ObjectMapper
String jsonStringOfInputParameters = toJSON(modelParameterList);
WebClient client = WebClient
.create("http://localhost:9000");
result = client.path(serviceEndpoint)
.query("tool", "myTool")
.query("input", jsonStringOfInputParameters)
.accept("application/json")
//tells cxf to convert the json to a string type upon return
.get(String.class);
// Return the json result as a string
return result;
}
your paramData variable is already a valid json. I do not think you need yo use JSON.Stringify() again.And what is this is the ajax call:
statusCode : {
200 : function(data) {
}
}
Status code is supposed to be coming from the server in response.
First, your ajax header should be like this:
headers: {
Accept: "application/json; charset=utf-8",
"Content-Type": "application/json; charset=utf-8"
},
url:
url: "http://localhost:9000/service/myService/sendInputs"
Second, you need to have MyModel with param1 field and Also setters and getters. And this can be your service method:
public String sendInputs(MyModel model)
{
//model.getParam1() will be "asdasd"
}
I am sending these data to Restful Web Service (Jersey) using jQuery code and the method POST:
var dataString = {"id":1,"status":"passed","session":"nothing"};
$.post("https://localhost:8443/pv01/ws/user/cookie", dataString);
And with this data, I am sending a cookie. The data in te cookie come from an external API.
The problem what I am facing is how to receive the cookie value and the dataString together.
Here's my Java code to read a Cookie :
#POST
#Path("cookie")
public String cookie(#CookieParam("L14c") String str) {
Logger.getLogger(Main.class.getName()).log(Level.INFO, "message : " + str );
return str;
}
And for the data, I can do like this :
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
#Path("cookie")
public String cookie(DataString dataString) {
Logger.getLogger(Main.class.getName()).log(Level.INFO, "message : " + dataString );
return "ok";
}
But when I combine the two methods to accept cookie and the JSON dataString, I got Error 415, Unsupported media type!
I tried to look on HTTP Headers, but I can access only cookies.
The problem is with the jQuery request. It looks like the Content-Type is defaulting to application/x-www-form-urlencoded. You should use a Browser debugger like Firebug. Makes it easier to spot these kind of things.
From what I've tested, it should work with something like
$.ajax({
url: theUrl,
type: "POST",
data: JSON.stringify(dataString),
dataType: "json",
contentType: "application/json",
success: function(response) {
alert(JSON.stringify(response));
}
});
I'm new to ajax and JSON (and programming in general), but what I'm trying to do is use ajax to convert my JSON object into a Java object but I keep getting "Required LocationsList parameter 'myJSONObject' is not present". Am I expecting too much of ajax here? I was told the fields in my LocationsList would be filled in automatically.
Ajax stuff:
function getAffectedFlowsForLocation(myJSONObject) {
//JSON.stringify(myJSONObject) looks like {"stations":["111", "222"],"stationGroups":["333"],"others":[]}
$.ajax({
url : baseUrl + "/locations/getFlowsAffectedByDelete",
type : "GET",
data : "{'myJSONObject':'" + JSON.stringify(myJSONObject)+ "'}",
dataType : "json",
contentType: 'application/json',
async : false,
success:function(data){
displayAffectedFlows(data);
},
error : function(){
// error is handled by global ajaxError()
success = false;
}
});
}
In the controller:
#RequestMapping(value = "/getFlowsAffectedByDelete", method = RequestMethod.GET)
#ResponseBody
public List<Map<String, String>> getFlowsAffectedByDelete(#RequestParam(value = "myJSONObject") final LocationsList locations) {
//returns a List<Map<String, String>>
}
My LocationsList:
public class LocationsList {
private List<Integer> stations;
private List<Integer> stationGroups;
private List<Integer> others;
//Getters and setters
}
Let me know if anything needs clarification.
Thanks
use
#RequestBody LocationsList locations
instead of
#RequestParam
I think you should change the way you are using the data attribute. From the jQuery documentation:
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests.
So, it should be an object:
data : { myJSONObject : JSON.stringify(myJSONObject) },
or a string:
data : "myJSONObject=" + JSON.stringify(myJSONObject),
I am trying to send a List of JSON objects into a post request. I keep getting a 500 error here. I feel like i am not setting up my variable in the Method definiton to the right data type but im not sure what it should be set too.
AJAX Request:
function post_request(json_data) {
$j.ajax({
url : '../api/createDisplayGroup/postHtmlVar/' + containerID[1] + '/' + containerType[1],
data: JSON.stringify(json_data),
dataType: 'json',
type : 'post',
contentType : 'application/json'
}).done(function(response) {
run_update(response);
}).error(function(jQXHR, textStatus, errorThrown) {
alert('error getting request');
});
};
Java REST Service (POST only):
#POST
#Path("/postHtmlVar/{containerId}/{contentType}")
#Consumes(MediaType.APPLICATION_JSON)
public List<TabDefinition> postHtml(#PathParam("containerId") String containerId, #PathParam("contentType") String contentType, List<JSONObject> displayGroups) {
Long contId = Long.parseLong(containerId);
Long contType = Long.parseLong(contentType);
//return convertToResponse(peopleFilterService.getDisplayGroups(contId, contType));*/
return testDisplayGroup();
}
You need to take the input json string as a #FormDataParam. I don't think your JAVA REST framework can marshal the json to a list of JSONObject. You may have to create a class representing the json data and define your method like this:
public List<TabDefinition> postHtml(#PathParam("containerId") String containerId, #PathParam("contentType") String contentType, #FormDataParam MyJSonDataClass myJsonDataClassObj) {