Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSONObject Alternative in Spring and Jackson

I need to pass a map back to the web application.

I'm used to encapsulating the map in a JSONObject

http://json.org/java/

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 ?

like image 647
user4127 Avatar asked Sep 24 '13 02:09

user4127


2 Answers

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 Lists, Maps and other JDK types just fine.

like image 108
StaxMan Avatar answered Sep 30 '22 16:09

StaxMan


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.

like image 27
Paulo Fidalgo Avatar answered Sep 30 '22 17:09

Paulo Fidalgo