Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return multiple values using JSON, jQuery and AJAX and Java

I am trying multiple values ​​to return from my server to AJAX in Java. For now, I use this approach, but it's not a good solution:

Javascript:

success: function(list) {
    var firstValue = list[0];
    var secondValue = list[1];
    var thirdValue = list[2];
}

Java:

ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
list.add(infoFirstValue());
list.add(infoThirdValue());
list.add(infoThirdValue());
String glist = gson.toJson(list);
response.getWriter().write(glist);

Is it possible to return several values ​​or an object or an other solution?

like image 563
Whitney R. Avatar asked Oct 22 '22 21:10

Whitney R.


1 Answers

If it helps, here's some code snippets based on yours above, showing how to switch to an object-style response instead of an array. Gson includes the class JsonObject which might be the simplest thing for you to use: http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/JsonObject.html

However, Gson's way more powerful than that -- you can actually just serialize a plain old Java object directly, which is probably more elegant than the intermediate step of converting existing data to a JsonObject (see this existing answer: https://stackoverflow.com/questions/1668862/good-json-java-library/1668951#1668951). At the very least, the info*Value() methods would probably be better served as methods of an object you were serializing. And instead of storing the returned object properties as functionally-scoped variables in JavaScript, I presume you could just pass the object around and access its properties.

JAVA

JSONObject rv = new JSONObject();
rv.add("firstValue", infoFirstValue());
rv.add("secondValue", infoSecondValue());
rv.add("thirdValue", infoThirdValue());

String gobject = gson.toJson(rv);
response.getWriter().write(gobject);

JAVASCRIPT

success: function(obj){
  var firstValue = obj.firstValue;
  var secondValue = obj.secondValue;
  var thirdValue = obj.thirdValue;
}
like image 189
mjk Avatar answered Oct 24 '22 18:10

mjk