Is there an easy way to return data to web service clients in JSON using java? I\'m fine with servlets, spring, etc.
I have found google-gson compelling. It converts to JSON and back. http://code.google.com/p/google-gson/ It's very flexible and can handle complexities with objects in a straightforward manner. I love its support for generics.
/*
* we're looking for results in the form
* {"id":123,"name":thename},{"id":456,"name":theOtherName},...
*
* TypeToken is Gson--allows us to tell Gson the data we're dealing with
* for easier serialization.
*/
Type mapType = new TypeToken<List<Map<String, String>>>(){}.getType();
List<Map<String, String>> resultList = new LinkedList<Map<String, String>>();
for (Map.Entry<String, String> pair : sortedMap.entrySet()) {
Map<String, String> idNameMap = new HashMap<String, String>();
idNameMap.put("id", pair.getKey());
idNameMap.put("name", pair.getValue());
resultList.add(idNameMap);
}
return (new Gson()).toJson(resultList, mapType);
Yup! Check out json-lib
Here is a simplified code snippet from my own code that send a set of my domain objects:
private String getJsonDocumenent(Object myObj) (
String result = "oops";
try {
JSONArray jsonArray = JSONArray.fromObject(myObj);
result = jsonArray.toString(2); //indent = 2
} catch (net.sf.json.JSONException je) {
throw je;
}
return result;
}
http://www.json.org/java/index.html has what you need.