Json Data Not mapped in the backend service - json

I have a Spring MVC web application and I have the following web service.
#RequestMapping(value = "/newBill", method = RequestMethod.POST)
public #ResponseBody ModelMap acceptNewBill(#ModelAttribute ("Bill") Bill newBill ){
Bill bill = new Bill();
bill.setTableName(newBill.getTableName());
bill.setRoom(newBill.getRoom());
bill.setCovers(newBill.getCovers());
ModelMap model = new ModelMap();
model.put("status", true);
return model;
}
The following Script performs the front end functions.
$('.done').click(function(){
var jsonObject = createJSON(".newBill");
jQuery.ajax({
url: "/newBill",
type: "POST",
data: {bill: JSON.stringify(jsonObject) },
dataType: "json",
beforeSend: function(x) {
if (x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
success: function(result) {
alert('sadgsd');
}
});
});
function createJSON(elementToConvert) {
jsonObj = [];
$( elementToConvert + " input").each(function() {
var id = $(this).attr("class");
var email = $(this).val();
item = {}
item [id] = email;
jsonObj.push(item);
});
return jsonObj;
}
The above createJSON function go through a provided html element and puts the values into an object! The click function performs the POST and the Post contains the following data.
bill [{"tableName":"326432"},{"room":"3462346"},{"covers":"3426234"}]
Now when I debug and check the service, the data which goes from the front end doesn't get mapped in the parameter. I checked whether the variable names are the same as the POST. They are the same! but the values doesn't get mapped! Can any one please help me with this issue.
Update :
I changed the service method to GET and passed a value as a URL variable. Then it got mapped in the service param. The problem is in the POST.

Instead of using #ModelAttribute in your controller use #RequestBody:
public #ResponseBody ModelMap acceptNewBill(#RequestBody Bill newBill) {
On the ajax call, set the content type to application/json and stringify the whole object instead of just the array:
jQuery.ajax({
url: "/newBill",
type: "POST",
data: JSON.stringify({bill: jsonObject}),
dataType: "application/json",
beforeSend: function(x) {
if (x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
success: function(result) {
alert('sadgsd');
}
});

Related

Posting JSON to controller MVC 5

I am posting JSON to my controller, but the problem is I am getting the correct count in list. i.e if JSON has two elements list has count of two but null data. Following is the code via I am making and sending the JSON. I've use TabletoJSON for making the JSON.
$('#productsObj').click(function () {
var rawMaterials = $('#productsTable').tableToJSON(
{
ignoreColumns: [3]
});
alert(JSON.stringify(rawMaterials));
console.log(rawMaterials);
$.ajax({
url: "/Supplies/insertRawMaterial",
type: "POST",
data: JSON.stringify(rawMaterials),
contentType: "application/json; charset=utf-8",
dataType: "json",
traditional: true,
error: function (response) {
alert(response.responseText);
},
success: function (response) {
alert(data);
alert(response);
}
});
});
Following is the controller action method which is receiving data.
public ActionResult insertRawMaterial(List<String> data)
{
if (data != null)
{
return Json("Success");
}
else
{
return Json("An Error Has occoured");
}
}
I am not sure where I am doing it wrong. Following is the JSON in alert.
[{"Raw Material Name":"Asphalt","Short Code":"AS02","Price":"20"}]
You cannot possibly expect to map this complex JSON structure to a list of strings (List<String>) that your controller action currently takes as parameter:
[{"Raw Material Name":"Asphalt","Short Code":"AS02","Price":"20"}]
So you may start by defining the appropriate view models that will reflect this structure (or almost, see the massaging technique required below):
public class MaterialViewModel
{
public string Name { get; set; }
public string ShortCode { get; set; }
public decimal Price { get; set; }
}
which your controller action will take as parameter:
public ActionResult insertRawMaterial(IList<MaterialViewModel> data)
{
...
}
and finally massage your data on the client to match the correct property names (name, shortCode and price of course):
// we need to massage the raw data as it is crap with property names
// containing spaces and galaxies and stuff
var massagedRawMaterials = [];
for (var i = 0; i < rawMaterials.length; i++) {
var material = rawMaterials[i];
massagedRawMaterials.push({
name: material['Raw Material Name'],
shortCode: material['Short Code'],
price: material['Price']
});
}
$.ajax({
url: "/Supplies/insertRawMaterial",
type: "POST",
data: JSON.stringify(massagedRawMaterials),
contentType: "application/json; charset=utf-8",
...
This being said, if the client side library you are currently using produces such undeterministic property names, you might consider replacing it with something more appropriate.

Losing values in JSON when passing to WEb API Action

I have an object (A) with a few properties, one of which is a LIST of abother type (B).
I have a Web API Action that takes in an A object as a parameter.
I am just testing that I can pass this object via JSON son I have a webform with some Javascript on it as follows.......
var tmpData = {
lid: "f8fdb980-ccb8-4a54-9b83-b73dd2d569ca",
aid: "8f6efc68-d747-42a4-b7d4-218951b66a97",
bid: "e9f5e5d2-5d3d-41ac-89dc-7586ec2a5286",
ps: []
};
tmpData['ps'].push({ "cid": "5a664dcc-8281-41f1-b81c-ae49499e12b8", "d": 5, "q": 2 });
tmpData['ps'].push({ "cid": "4e9a30e0-c741-4708-88d7-8db4941c17cc", "d": 10, "q": 2 });
var myJSON = JSON.stringify(tmpData);
//Call the action to get the list in JSON format
url = "http://localhost:64878/home/TakeTestBasketAddItemsRequest";
$.ajax({
url: url,
type: 'POST',
cache: false,
data: myJSON,
success: function (resultantData) {
var s = resultantData;
pResults.innerHTML = s;
}
});
This gets to the action OK and the object has 2 items in the "ps" property.
Howeverm the values in these 2 items are lost and I am left with zeros / uninitialised values.
Whay am I losing the values of the list items?
For clarity - here is my Action also.
[HttpPost]
public ActionResult TakeTestBasketAddItemsRequest(ECodeBasketRequest model)
{
try
{
var sb = new StringBuilder();
sb.AppendLine(String.Format("LocationBridgeId: {0}{1}", model.lid, Environment.NewLine));
sb.AppendLine(String.Format("ApplicationBridgeId: {0}{1}", model.aid, Environment.NewLine));
sb.AppendLine(String.Format("BasketId: {0}{1}", model.bid, Environment.NewLine));
foreach (var p in model.ps)
{
sb.AppendLine(String.Format("CategoryBridgeId: {2} Denomination: {0} Quantity: {1}{3}", p.d, p.q, p.cid, Environment.NewLine));
}
return Content(sb.ToString());
}
catch (Exception ex)
{
return Content(string.Format("Problem: {0}", ex.ToString()));
}
}
As I said, I am just testing at the moment so would love to get to the bottom of this. Thanks in advace,
Ant
Apologies all - but it seems I ommitted the content type....
contentType: "application/json"
It's misleading when some of the object is reconstruucted OK and the rest isn't....but hey ho - It's Friday and it's working..
Well hopefully it will help someone else out.......
So I now find that this works.....
$.ajax({
url: url,
type: 'POST',
cache: false,
**contentType: "application/json",**
data: myJSON,
success: function (resultantData) {
var s = resultantData;
pResults.innerHTML = s;
}

Return json array from client to spring controller

I need to send data from the client html back to the spring controller.
I have a controller which generates a Json array whichh I sent via ajax to the html side when requested.
That functions well.
The Problem is I need to send the Json array back to another controller for evaluation and changes.
If I post the data and assign an class object of the original class I get the error " Bad request" and it didn't work.
If I assign an object in the controller which consumes the post. That works
but I get an hashmap for which I dont know how to access.
I cant cast it to another class nor access it to work with it.
Since I am new to this can someone give me an advice how to consume the post
on the receiving controller side.
Thanks
Khelvan.
Controller code ist stated below
controller 1 for Get
#RequestMapping("/Person")
#ResponseBody
public ArrayList<Person> ajax_Person_array()
{
ArrayList<Person> Dummy = new ArrayList<Person>();
for ( x=0; x < 5; x++ ){
Dummy.setName("Alfon");
Dummy.setID("5");
Dummy.setStree("Delta");
Dummy.setName("Neutral");
Person.add(Dummy);
}
return Dummy;
}
Controller 2 for post
#RequestMapping(value="/ajax", method=RequestMethod.POST, consumes = "application/json")
//public #ResponseBody String post( #RequestBody Object ajax_Person_array()) {
public #ResponseBody String post( #RequestBody ArrayList<Person> ajax_Person_array()) {
System.out.println("First TEST");
String Success = "OK";
return Success;
}
Html : get ajax
var ajax_data;
$.ajax({
url: "http://localhost:8080/Person",
async: false,
dataType:'json',
cache: false,
success: function (data) {
ajax_data = data;
alert("success ");
},
error:function(){alert("something went wrong ");}
});
}
Html post ajax
$.ajax({
url: "http://localhost:8080/ajax",
type: 'POST',
dataType: 'text',
data: ajax_data,
// data: JSON.stringify(ajax_data),
contentType: 'application/json',
success: function(data) {
alert(data);
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
document.write(data);
}
});
#RequestMapping (value="/ajax", method=RequestMethod.POST, consumes = "application/json")
public #ResponseBody JSONObject post( #RequestBody JSONObject person) {
//Pass data to a service to process the JSON
}
For your ajax request, do not set dataType to 'Text'. Set it to JSON
$.ajax({ url: "http://localhost:8080/ajax",
type: 'POST',
dataType: 'json',
data: JSON.stringify(ajax_data),
contentType: 'application/json',
success: function(data) {
alert(data);
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
document.write(data);
}
});

Passing in JSON array to spring MVC Controller

I am trying to pass a JSON array into spring MVC Controller like such:
var myList = new Array();
data._children.forEach( function (d) {
myList.push( {NAME: d.name, TYPE: d.TYPE, FDATE: d.FDATE } );
});
$.post("/ListRequest", {myList: myList});
The controller looks as such:
#RequestMapping(value="/ListRequest", method = RequestMethod.POST)
public void ListRequest(#RequestParam("myList") myList tempmyList )
{
System.out.println(tempmyList);
}
The class myList defined as such:
public class MyList {
private List<ListT> ListT;
public List<ListT> getListT() {
return ListT;
}
public void setListT(List<ListT> listT) {
ListT = listT;
}
}
ListT class:
public class ListT {
private String NAME;
private String TYPE;
private Long FDATE; ...
I keep getting this error:
HTTP Status 400 - Required myList parameter 'myList' is not present
Also tried this request:
$.ajax({
type: "post",
url: "ListRequest", //your valid url
contentType: "application/json", //this is required for spring 3 - ajax to work (at least for me)
data: JSON.stringify(myList), //json object or array of json objects
success: function(result) {
//do nothing
},
error: function(e){
alert('failure');
}
but get this error: JBWEB000120: The request sent by the client was syntactically incorrect.
try to add this to you ajax call it should fix the unsupported response :
headers : {
'Accept' : 'application/json',
'Content-Type' : 'application/json'
},
this is a full example of ajax call that is working for me :
$.ajax({
dataType : "json",
url : this.baseurl + "/dataList",
headers : {
'Accept' : 'application/json',
'Content-Type' : 'application/json'
},
data : JSON.stringify(params),
type : 'POST',
success : function(data) {
self.displayResults(data);
},
error : function(jqXHR,textStatus,errorThrown ){
showPopupError('Error','error : ' + textStatus, 'ok');
}
});
Even I was facing same problem.
My client request was right and generated proper json file.
but still i was getting same error.
I solved this error using #JsonIgnoreProperties(ignoreUnknown = true) in pojo class.
refer this link.
Spring MVC : The request sent by the client was syntactically incorrect
You can try
#RequestParam("myList") myList tempmyList
#Param myList tempmyList
in addition, class names must begin with a capital letter.

How to pass a JSON object to an action

I have the following jQuery code in a View in MVC3. I want to load a partial view (named OffshoreECore) in a div (#Form) depending on the JSON object passed in the success function. Here's the code:
var inputParamtrs = { 'HeadId': $('#ExpenseId').val(), MProjid': $('#MProjid').val() };
$.ajax({
type: "POST",
url: "/Expenses/Edit",
data: inputParamtrs,
success: function (json) {
('#Form').load('#Url.Action("OffShoreECore", *What comes here ?!?*)');
}
Thanks.
The second parameter of load() is the data which should be sent to the specified URL along with the request. To send your JSON string, try this:
success: function (json) {
$('#Form').load('#Url.Action("OffShoreECore")', json);
}
You example code is also missing a ' delimiter from the second key in inputParamtrs and the $ from the selector in success, but I guess they're just typos.
$.getJSON("/Expenses/Edit",
{
HeadId: $('#ExpenseId').val(),
MProjid: $('#MProjid').val()
},
function (data) {
elementForResult.innerHTML = data;
});
In Controller:
public JsonResult Edit(int HeadId, int MProjid)
{
...
var result = SerializeControl("~/Views/Expenses/Edit.cshtml", null);
return Json(result, JsonRequestBehavior.AllowGet);
}
private string SerializeControl(string controlPath, object model)
{
var control = new RazorView(ControllerContext, controlPath, null, false, null);
ViewData.Model = model;
var writer = new HtmlTextWriter(new StringWriter());
control.Render(new ViewContext(ControllerContext, control, ViewData, TempData, writer), writer);
string value = writer.InnerWriter.ToString();
return value;
}