JSONObject Alternative in Spring and Jackson
Solution 1
Jackson has com.fasterxml.jackson.core.JsonNode
, and specific subtypes like ObjectNode
.
These form so-called Tree Model
, which is one of 3 ways to handle JSON with Jackson -- some other libraries (like org.json
) only offer this way.
So you should be able to just use JsonNode
instead; there is little point in using org.json
library; it is slow, and has outdated API.
Alternatively you can just use java.util.Map
, and return that. Jackson can handle standard List
s, Map
s and other JDK types just fine.
Solution 2
If you need to manipulate the output, ie, you don't want to provide all the fields of the object you can use JSonArray:
@RequestMapping(value = "/api/users", method = RequestMethod.GET)
public
@ResponseBody
String listUsersJson(ModelMap model) throws JSONException {
JSONArray userArray = new JSONArray();
for (User user : userRepository.findAll()) {
JSONObject userJSON = new JSONObject();
userJSON.put("id", user.getId());
userJSON.put("firstName", user.getFirstName());
userJSON.put("lastName", user.getLastName());
userJSON.put("email", user.getEmail());
userArray.put(userJSON);
}
return userArray.toString();
}
Use the example from here
Otherwise if you add jackson to your dependencies and set the controller method anotatted with @ResponseBody
the response will automatically mapped to JSON. Check here for a simple example.
Related videos on Youtube
user4127
Updated on June 21, 2022Comments
-
user4127 almost 2 years
I need to pass a map back to the web application.
I'm used to encapsulating the map in a JSONObject
But since I am using Spring and Jackson Haus.
is there an easier way to maintain the pojo? May I can just annotate the MAP ?
-
Arun P Johny over 10 yearsSo in your project you have jackson available right... then if you return the map from the controller with @ResponseBody annotation then it will get automatically converted into a json object by spring converters
-
-
user4127 over 10 yearspardon me but if it is a submit request(don't know the actual term) .. it won't forward me to another page.