How to convert JSon Object to Java Object? - java

Can Anyone help me on this, i m trying to convert complex json object send through ajax into a object. so that i can use this object to pass into my model.
The JSP code is:
function callRemovefilter()
{
var jsonObjects = {
address1: "Address_1",
city: "City",
pin: "PIN"
};
var jsonObjects2 = {
locality:"Loc1",
shippingType:"Regular",
shippingCost:20
};
var cust= JSON.stringify(jsonObjects);
var sales=JSON.stringify(jsonObjects2);
jQuery.ajax({
url: "http://localhost:8080/OnlineStore/kmsg/grocery/SaveSalesOrder",
type: "GET",
data: {CustomerInfo:cust,SalesModel:sales},
dataType: "json",
beforeSend: function(x) {
if (x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
success: function(result) {
//Write your code here
}
});
}
// The controller code is
#RequestMapping(value = "/SaveSalesOrder", method = RequestMethod.GET)
#ResponseStatus(value=HttpStatus.OK)
public #ResponseBody String SaveCustomerOrder(#RequestParam Map<String,String> requestParams) throws Exception
{
ObjectMapper objectMapper = new ObjectMapper();
SalesCommandObject salesCommandObject= new SalesCommandObject();
salesCommandObject = objectMapper.readValue(body, SalesCommandObject .class);
return "Success";
}
// Code of JSP to send object to controller
var salesCommandObject = {}; salesCommandObject.CustomerInfo =
{
"address1": "Address_1",
"city": "City",
"pin": "PIN"
};
salesCommandObject.SalesModel =
{
"locality":'Loc1',
"shippingType":'Regular',
"shippingCost":20
};
$.ajax
({
type: "POST",
dataType : 'json',
async : true,
url: "http://localhost:8080/OnlineStore/kmsg/grocery/SaveSalesOrder",
data : JSON.stringify(salesCommandObject),
}).done(function(data,type,xml)
{
console.log(data);
}).fail(function()
{
alert("Something Bad Happened, Service failed");
})

Send objects, not jsonstrigs. And in controller in your method SaveCustomerOrder get an object, not Map, like:
#RequestMapping(value = "/SaveSalesOrder", method = RequestMethod.GET)
#ResponseStatus(value=HttpStatus.OK)
public #ResponseBody String SaveCustomerOrder(#RequestParam CustomerInfo ci, #RequestParam SalesModel sm) throws Exception
{
//your logic here
return "Success";
}
And add getters and setters to appropriate classes(i.e CustomerInfo, SalesModel) like:
`public class SalesModel{
private String sale_id;//or whatever field or property you need
public String getSale_Id() {
return sale_id;
}
public void setSale_Id(String si) {
this.sale_id = si;
}
}`

Related

405 Error : multipart/form-data with Spring

I am trying to send a Json string along with multiple files into my Spring Controller, however it would always give me a 405 Method Not Allowed Error, what am I doing wrong?
Javascript Code:
var formdata = new FormData();
formdata.append('user', JSON.stringify(userData));
files.forEach(file=> {
formdata.append('files', file);
});
jQuery.ajax({
url: "user/submitForm",
type: "POST",
data: formdata,
enctype: 'multipart/form-data',
processData: false,
contentType: false,
success: function (data)
{
console.log("SUCCESS");
},
error: function (request, status, error) {
alert(status + " : " + JSON.stringify(request));
}
});
Controller in Spring:
#PostMapping(value= "/submitForm", consumes = {
MediaType.APPLICATION_JSON_VALUE,
MediaType.MULTIPART_FORM_DATA_VALUE })
public ResponseEntity<?> userRegistration( #RequestPart("user") String user,
#RequestPart("files") List<MultipartFile> files, BindingResult bindingResult) {
ObjectMapper obj = new ObjectMapper();
User newUser = new User();
newUser = obj.readValue(user, User.class);
System.out.println("User : \n"+ newUser.toString());
System.out.println("Files : \n"+ files.toString());
return null;
}
This was the solution that I found from Antonio112009's answer
SOLUTION
#PostMapping(value = "/submitForm")
public ResponseEntity<?> userRegistration(
#RequestParam("user") String user,
#RequestParam(value = "files", required = false) List<MultipartFile> files) {
ObjectMapper obj = new ObjectMapper();
User userObj = new User();
.
.
.
}
I use another solution, who works as expected and are a bit more flexible from my point of view.
Front-end part is in Typescript.
Front-end
var formData = new FormData();
options.files.forEach(function (file) {
formData.append(file.name, file);
});
formData.append("myParam", "coucou");
var xhr = new XMLHttpRequest();
xhr.open("POST", "/rest/upload");
xhr.onload = function () {
var data = JSON.parse(xhr.responseText);
options.callback("success", options.files.map(function (file) {
return {
file: file,
content: data[file.name]
};
}));
};
xhr.send(formData);
Back-end (Java Spring)
#RestController
#RequestMapping(value = "/rest")
public class UploadController {
#PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<Boolean> upload(MultipartHttpServletRequest request) {
// Get param
Object myParam = request.getParameter("myParam");
// Get iteretaor on all files
Iterator<String> iterator = request.getFileNames();
MultipartFile multipartFile = null;
while (iterator.hasNext()) {
multipartFile = request.getFile(iterator.next());
final String fileName = multipartFile.getOriginalFilename();
final String fileSize = String.valueOf(multipartFile.getSize());
// Add logic ....
}
}
return new ResponseEntity(true);
}

Send a data through Ajax, and the background never receives it

The foreground sends an ID to the background through Ajax, but the background never receives it. I have been troubled by this problem for a whole day, and I really need your help.Here are my JS and Controller and error messages
$('.category-wrap').on('click', '.now .delete', function (e) {
var target = e.currentTarget;
var pc = target.dataset.id;
var pcId = {'pcId':pc};
$.confirm('sure?',function () {
$.ajax({
url: deleteUrl,
type: 'POST',
data: pcId,
contentType: 'application/json',
cache: false,
success: function (data) {
if (data.success) {
$.toast('successfully delete!');
getList();
} else {
$.toast('Delete failed!');
}
}
});
})
});
#RequestMapping(value = "/removeproductcategory", method = RequestMethod.POST)
#ResponseBody
public Map<String, Object> removeProductCategory(#RequestBody Integer pcId,
HttpServletRequest request)
{...}
image 1
image 2
you send a json request var pcId = {'pcId':pc}; and try to receive an Integer #RequestBody Integer pcId
try to define a Pojo like this
class RequestData {
public Integer pcId;
}
and modifiy controller method parameter
#RequestMapping(value = "/removeproductcategory", method = RequestMethod.POST, consumes = "application/json" )
#ResponseBody
public Map<String, Object> removeProductCategory(#RequestBody RequestData pcId,
HttpServletRequest request)

Getting exception while passing JSON data from JQUERY to java controller

I am passing JSON data from jQuery to my Java controller and I am using #RequestBody, but I am getting an exception saying:
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported
The data which I am passing is:
myData = {
"source": "CSS",
"type": "CSS2",
"typeValue": "value",
"textarea_value": " desc"
}:
The AJAX call I am using to pass this data is:
$.ajax({
url: './common/deleteData',
type: 'POST',
data: myData,
success: function(data) {
alert("Successfully Deleted Source..");
},
error: function(data) {}
});
My Java Controller is as below
#RequestMapping(value = "/common/deleteData", method = RequestMethod.POST, consumes = {"application/x-www-form-urlencoded; charset=UTF-8"})
public String deleteData(#RequestBody SourceDelete sourcedelete, final HttpServletRequest request, final RedirectAttributes rdtAttribs) throws ApplicationException
{
LOGGER.entry("Deleting the Merge Preference Details");
System.out.println(sourcedelete.getSource());
return null;
}
My POJO object is as below:
public class SourceDelete {
private String source;
private String type;
private String typeValue;
private String textarea_value;
//Setters and Getters
}
Can someone please help me figure out why I am getting this error and how I should fix it.
remove the #RequestBody annotation,
#RequestMapping(value = "/common/deleteData", method = RequestMethod.POST, consumes = {"application/x-www-form-urlencoded; charset=UTF-8"})
public String deleteData(SourceDelete sourcedelete, final HttpServletRequest request, final RedirectAttributes rdtAttribs) throws ApplicationException
{
LOGGER.entry("Deleting the Merge Preference Details");
System.out.println(sourcedelete.getSource());
return null;
}

JQuery, AJAX, POST request, parameters lost

My web application is basen on Spring MVC (4.0.5).
I'm trying to send a POST request through AJAX, using jQuery (v. 2.1.1):
function deleteItem(id) {
alert("Deleting " + id);
$.ajax({
url: "ajax/delete_item",
type: 'POST',
dataType: 'html',
data: {"id": id},
contentType: 'application/json',
mimeType: 'application/json',
success: function(data) {
var txt = data;
$('#message').html(txt);
},
error: function(data, status, err) {
$('#message').html(err);
}
});
}
The Controller's method is called successfully but there are no parameters in the request:
#RequestMapping(value = "/ajax/delete_item", method = RequestMethod.POST)
public #ResponseBody String ajaxDelete(HttpServletRequest request) {
Enumeration<String> en = request.getParameterNames();
while (en.hasMoreElements()) {
String pname = en.nextElement();
System.out.println("//// " + pname); // just for test
}
String idStr = request.getParameter("id");
Integer id = Integer.parseInt(idStr);
//...
Why the request parameter is lost? Not just the value, the parameter itself is also lost.
What's wrong here?
If you are passing content type contentType: 'application/json' from ajax then add that settings in Spring method declaration as below: ( add produces = "application/json" in definition)
#RequestMapping(value = "/ajax/delete_item", method = RequestMethod.POST , produces = "application/json")
public #ResponseBody String ajaxDelete(HttpServletRequest request) {
also there's one more caveat that,
You are mentioning both datatype and mimeType but it is not uniform.
mimeType: 'application/json' should be written with dataType: 'json' and not html.
I am not 100% sure what is wrong with your solution but I can give you an example that works for me
The AJAX request using Jquery :
// Do AJAX
$(function () {
$.post(mobileUrl + "/leave/requestLeave",
{ startDate: startDate, endDate: endDate, leaveTypeId: leaveTypeId,
notes: notes, isStartDayHalfDay: isStartDayHalfDay, isHalfDayEndDay: isHalfDayEndDay },
function (response) {
$('#feedbackTextArea').show();
}
);
});
And the controller method
#RequestMapping(value = "/requestLeave", method = RequestMethod.POST)
#ResponseBody
public String createOrUpdateNewForm(String startDate, String endDate, String leaveTypeText, String leaveTypeId,
String notes, String isStartDayHalfDay, String isHalfDayEndDay) {
startDate = new DateTime(startDate).toDate() etc
}
}
One thing to remember is that the parameter names in the ajax request should match the names of the variables in the controller method implementation
$("#drpop").change(function () {
var code = $(this).val();
$.ajax({
url: '/Ordering/OrderingTable',
type: 'post',
datatype: 'json',
data: { OperCode: code },
success:function(msg){
alert(msg);
} }); });
[HttpPost]
public ActionResult OrderingTable(string OperCode)
{
Orderingbll order = new Orderingbll();
var result = order.ListCategory(OperCode);//here you write your code
return Json(result,JsonRequestBehavior.AllowGet);
}

Calling Java Rest API from javascript as JSONP returns invalid label error

i have created a java webservice to return country list
#RequestMapping(value = "/getcountrylist", method = RequestMethod.GET, headers = "Accept=application/json")
public #ResponseBody
#ApiIgnore
Object getcountrylist(#RequestParam String pvtToken,
#RequestParam String lan) {
System.out.println(API_TAG + "Request recevied to get CountryList");
System.out.println("DB:"+dbName);
if (!this.pvtToken.equals(pvtToken)) {
CountryList countryList = new CountryList();
return new ResponseEntity<CountryList>(countryList,
HttpStatus.UNAUTHORIZED);
}
CountryList countryList = avlMobileAPIService.getCountryList(lan);
return new ResponseEntity<CountryList>(countryList, HttpStatus.OK);
}
i need to call the above webservice from javascript as JSONP, i wrote the following javascript code as below
function buttonClick(){
$.ajax({
type: "GET",
dataType: "jsonp",
crossDomain: true,
url: "http://localhost:8080/api/getcountrylist",
data: {pvtToken:"JXku56AE0067YtRUSAZEE",lan:"en"},
Accept: "application/jsonp",
jsonpCallback: function(data, status){
alert('callback');
alert(data);
},
success: function(data, status){
alert('sucess');
},
});
}
Above function call the webservice and returns the list, but shows "invalid label error" on client side.
{"countrylist":[{"countryId":"4","countryCodeAlpha2":"AF","countryCodeAlpha3":"AFG","countryName":"Afghanistan ","isdCode":"93"},{"countryId":"5","countryCodeAlpha2":"AL","countryCodeAlpha3":"ALB","countryName":"Albania ","isdCode":"355"},{"countryId":"6","countryCodeAlpha2":"DZ","countryCodeAlpha3":"DZA","countryName":"Algeria ","isdCode":"213"},{"countryId":"7","countryCodeAlpha2":"AS","countryCodeAlpha3":"ASM","countryName":"American Samoa ","isdCode":"684"}]}
i found in some article it says, the that ajax call expects JSONP , but return JSON data.
What is the solution?
reffer this link
http://www.iceycake.com/2012/06/xml-json-jsonp-web-service-endpoints-spring-3-1/
or try in this simple way
#RequestMapping(value = "/mobile_getcountrylist", method = RequestMethod.GET, produces = {"application/x-javascript"})
#ResponseBody
public Object mobile_getcountrylist( #RequestParam("callback") String jsonpCallback) {
System.out.println(API_TAG + "Request recevied to get CountryList");
CountryList countryList = avlMobileAPIService.getCountryList("en");
//countryList.setJsonCallback(jsonpCallback);
return convertToJsonP(countryList,jsonpCallback);
}
private String convertToJsonP(Object o,String jsonpCallback){
String outputmessage=null;
ObjectMapper mapper = new ObjectMapper();
try {
outputmessage=mapper.writeValueAsString(o);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(outputmessage!=null){
outputmessage=jsonpCallback + "(" + outputmessage + ")";
}
return outputmessage;
}
Javascript code
$.ajax({
type: 'GET',
url: 'http://localhost:8080/api/mobile_getcountrylist',
crossDomain: true,
async: false,
jsonpCallback: 'jsonpCallback',
dataType: 'jsonp',
contentType:'application/json',
success: function(data) {
alert('ok');
}
});

Categories