I am using Spring 4 and Jackson. I am trying to return a LinkedHashMap from controller to Ajax Response.
However when Jackson is converting it to JSON the order of keys in the LinkedHashMap is getting lost.
How can I maintain the order of records.
Controller code:
#ResponseBody
#RequestMapping(value = "/getLevel2", method = RequestMethod.POST)
public LinkedHashMap<String, String> getLevel2(HttpServletRequest request)
{
System.out.println("In getLevel2"+request.getParameterNames());
String catId=request.getParameter("catId");
String fkey=request.getParameter("key");
LinkedHashMap<String, String> h=categoryService.getCategoryLevel2Map(2100,fkey);
System.out.println(h);
return h;
}
Ajax call:
var jqxhr = $.ajax({
type: "POST",
url:"/a2bNext/getLevel2",
cache: false,
data:'catId='+ catId+'&key='+selectedValue
} )
.done(function(data) {
$("#level2").empty();
for (var key in data) {
value=data[key];
isLeaf=value.split('::')[1];
value=value.split('::')[0];
if(isLeaf==1)
{
option = $('<option></option>').attr("value", key).text(value);
$("#level2").append(option);
}
else
{
option = $('<option></option>').attr("value", key).attr("class","subdivide").text(value);
$("#level2").append(option);
}
}
$("#level2").show();
})
.fail(function() {
alert( "error1" );
})
.always(function() {
//alert( "complete" );
});
});
Could anyone suggest how can I get the keys in ajax response in the same order as in LinkedHashMap.
Related
I'm using ajax with GET method, I'm waiting receive a JSON but sometime the response is null and get the error:
SyntaxError: Unexpected end of JSON input
ajax:
$(document).ready(function() {
$("#form_data").submit(function(e) {
e.preventDefault()
var expediente = $('#expediente').val();
$.ajax({
url : 'buscarPaciente' + '?expediente=' + expediente,
dataType : "json",
type : "GET",
contentType : 'application/json',
mimeType : 'application/json',
success : function(data) {
console.log(data.nombre);
},
error : function(xhr, status, error) {
console.log(error)
}
});
})
});
in the controller:
#RequestMapping(value="/buscarPaciente", method = RequestMethod.GET)
public #ResponseBody MntPaciente
buscarPaciente(#RequestParam("expediente") String expediente) {
MntPaciente mntPaciente = servicePx.findByexpediente(expediente);
if (mntPaciente!= null) {
return mntPaciente;
}
return null; // Should I return an empty json? how?
}
There are several ways to do it. The first is to configure the JSON library that used to serialise JSON .In case of Jackson , you can use #JsonInclude to exclude all the empty properties not to serialise and just return an empty MntPaciente :
#JsonInclude(Include.NON_EMPTY)
public class MntPaciente {
}
public #ResponseBody MntPaciente buscarPaciente(#RequestParam("expediente") String expediente) {
....
return new MntPaciente();
}
To apply globally rather to configure for each object , you could use
ObjectMapper om = new ObjectMapper();
om.setSerializationInclusion(Include.NON_EMPTY);
The other way is to change the controller method to return ResponseEntity and directly return a empty JSON string :
public #ResponseBody ResponseEntity buscarPaciente(#RequestParam("expediente") String expediente) {
if (mntPaciente!= null) {
return ResponseEntity.of(mntPaciente);
}else{
return ResponseEntity.of("{}");
}
}
var form_data = {
itemid: globalSourceItem.substr(globalSourceItem.indexOf("-") + 1),
columnName: jqInputs[0].value,
displayName: jqInputs[1].value,
format: jqInputs[2].value,
KBE: jqInputs[3].value,
dgroup: jqInputs[4].value,
dupkey: jqInputs[5].value ,
measurement: jqInputs[6].value ,
times: new Date().getTime()
};
// console.log(form_data);
// console.log($("#tourl").html());
$.ajax({
url: $("#tourl").html(),
type: 'POST',
datatype: 'json',
data: form_data,
success: function(message) {
var j_obj = $.parseJSON(message);
// console.log(j_obj);return false;
if (j_obj.hasOwnProperty('success')) {
toastr.info('Item updated successfully');
setTimeout(function(){
window.location.reload();
},1000);
} else {
toastr.info('There was a problem.');
}
},
error: function(xhr, textStatus, errorThrown)
{
toastr.info('There seems to be a network problem. Please try again in some time.');
}
});
}
Hii friends , this code is working for php and i need to send the same data to the spring mvc through the ajax , can anyone please help me with the exact solution where to make changes as Iam struckup with the same doubt for like 2 weeks...
public class TestController {
#RequestMapping(value = "url", method = RequestMethod.POST)
public ModelAndView action(#RequestBody FormData formData) {
...
}
}
public class FormData {
private String itemid;
public String getItemid() {
return itemid;
}
public void setItemid(String itemid) {
this.itemid = itemid;
}
//...
}
Try sth like this. You should be able to map JSON Object to Java Object.
Maybe you could use annotation #ResponseBody and convert JSONObject to String:
#RequestMapping(value = "/ajax", method = RequestMethod.POST, produces="application/json")
#ResponseBody
public String ajax(#RequestBody ListDataDefinition listDataDefinition) {
System.out.println("id="+listDataDefinition.getItemid());
int i=SchemaDAOI.updateldd(listDataDefinition);
String message="success";
JSONObject obj = new JSONObject();
try {
obj.put("success", "success");
}
catch (JSONException e) {
e.printStackTrace();
}
if(i==1){
System.out.println("success");
}
else{
System.out.println("failure");
}
return obj.toString();
}
}
If you send String to View as ResponseBody and set produces as JSON it should be treated as pure JSON RQ.
Can anyone tell what am I doing wrong here???
In bankbonejs, I am trying to make a POST request. Here is my code: Im using tomcat server.
$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
saveDetails: function (ev) {
var abcDetails= $(ev.currentTarget).serializeObject();
var abc= new ABC();
bank.save(abcDetails, {
success: function (abc) {
router.navigate('', {trigger:true});
}
});
return false;
}
Call goes to the server side (Tomcat) but the post request params are coming as null. I have checked var abcDetails just before requesting the save has the values populated correctly. Also, checked by sending post request thru PostMaster to make sure that values are passed from the client side correctly. However, on the server side these posted request params are null. I am some how stuck here.vAppreciate help in this regard.
Server Side
.
#RequestMapping(value = { "/postedValues" }, method = RequestMethod.POST)
public String getpostedValues( HttpServletResponse response, HttpServletRequest request) throws Exception {
JSONArray jsonarray = new JSONArray();
JSONObject jsonobj = new JSONObject();
String _id = StringEscapeUtils.escapeHtml4(request.getParameter("id"));
String col1= StringEscapeUtils.escapeHtml4(request.getParameter("col1"));
String col2= StringEscapeUtils.escapeHtml4(request.getParameter("col2"));
Also,
Enumeration paramaterNames = request.getParameterNames();
while(paramaterNames.hasMoreElements() ) {
System.out.println(paramaterNames.nextElement());
}--> observation:does not go inside the while loop
This is homePage.jsp code :
<button id="bilgial" onclick="getVector(id)">Get Vector</button>
<input type="text" id="hs">
and this is getVector(id) function :
var id = document.getElementById("hs").value;
function getVector(id) {
ajax({
type: "GET",
path: "/getGeoJson",
data: {id: id},
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
success: function (data) {
var parser = new OpenLayers.Format.GeoJSON();
var feature = parser.read(data.data);
if (feature.length != 0) {
feature[0].attributes.id = data.id;
}
vectors.addFeatures(feature);
}
});
}
this is my controller get method :
#Controller
public class HSpatialController {
SavegeojsonManager add = new SavegeojsonManager();
#RequestMapping(value = "/getGeoJson", method = RequestMethod.GET)
#ResponseBody
public GeoJSON getGeoJson( final HttpServletRequest request,#RequestParam("id") final String vectorId) {
return add.get(vectorId);
}
}
and this is SavegeojsonManager class and get method :
public GeoJSON get(String id) {
GeoJSON geoJson = new GeoJSON();
EntityManager em = HibernateSpatialJPA.createEntityManager();
em.getTransaction().begin();
Query query = em.createQuery("select e from SavegeojsonEntity ????")
query.setParameter("", ??);
return geoJson;
}
or how can I do otherwise ?
I want to was eat with the number that was in the database that you want to take the data from the TextBox equally with data GetData ?
So code should be like this:
public GeoJSON get(String id) {
GeoJSON geoJson = new GeoJSON();
EntityManager em = HibernateSpatialJPA.createEntityManager();
em.getTransaction().begin();
Query query = em.createQuery("from SavegeojsonEntity s where s.id = :id")
query.setParameter("id", Integer.valueOf(id));
List entityList = query.getResultList();
if(entityList != null && !entityList.isEmpty()){
SavegeojsonEntity entity = (SavegeojsonEntity)entityList.get(0);
geoJson.setType(entity.getVectorType());
if(entity.getVectorType().equals("Point")){
geoJson.setData(entity.getPoint());//or entity.getXXX() since you need to get point data,
} else if(...){
//same for Polygon/MultiPolygon/StringLine and so on
}
}
em.getTransaction().close();
return geoJson;
}
How can I return IEnumerable's values with using ajax. Here is my script:
$.ajax({
type: "get", url: "street", data: { a: value2 },
success: function (data) {
alert(data);
}
And here is my controller method:
[HttpGet]
public string street(string a)
{
EmlakServicesClient client = new EmlakServicesClient();
client.ClientCredentials.UserName.UserName = "service_test";
client.ClientCredentials.UserName.Password = "..";
client.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;
Street[] list =client.GetStreet(Convert.ToInt32(a));
return ("" + list.FirstOrDefault().StreetName);
}
As you can see at top I get value but with First Value so how can I get these all values from IEnumarable?
You should use JSON:
return Json(list, JsonRequestBehavior.AllowGet);
You will need to change your action method to return ActionResult.
return the Collection as JSON
public ActionResult GetsomeItems(int someId)
{
var someCollection=GetListOfItemsFromSomeWhere(someId)
return Json(someCollection,JsonRequestBehaviour.AllowGet);
}
I tripped over this while doing a Google search on how to return JSON results using ASP.NET Web API 2. In case someone else is looking for the same solution, here is the solution that worked for me:
// GET: api/Users
public HttpResponseMessage Get()
{
var users = UserManager.Get(); // returns IEnumerable
return Request.CreateResponse(HttpStatusCode.OK, users);
}
You can learn more about HttpResponseMessage here.