JSONObject Alternative in Spring and Jackson

14,418

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 Lists, Maps 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.

Share:
14,418

Related videos on Youtube

user4127
Author by

user4127

Updated on June 21, 2022

Comments

  • user4127
    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

    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 ?

    • Arun P Johny
      Arun P Johny over 10 years
      So 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
    user4127 over 10 years
    pardon me but if it is a submit request(don't know the actual term) .. it won't forward me to another page.