Search code examples
javajsonspringspring-mvcmarshalling

Spring MVC: How to return multiple JSONs, plus other attributes, in single controller method?


I am using Spring 3.2 and Spring MVC. Jackson libraries are included in my setup.

I have a page which, on initial load, needs to populate two data sources for Dojo dropdown boxes (data sources are Strings in the JSON format) and two textboxes. I am assuming I can add these to the Model as four Strings before returning.

I find plenty of examples where a controller with a method annotated with @ResponseBody returns a single JSON in response to an AJAX request, but I can't find any examples of how to handle the above situation (which is not a response to an AJAX request, and includes multiple JSONs as well as simple Strings).

  1. Is my approach of returning four Strings (two containing JSONs, and two containing the textbox contents) in the Model sound?

  2. If the answer to (1) above is Yes: How to pull in two List objects into the method as JSONs and store them in Strings?


Solution

  • Found the Solution

    I found the solution to the second part of my question (#2). It is rooted in basic use of Jackson's ObjectMapper to serialize a List object into a String containing JSON notation:


    @RequestMapping()
    protected String initPage(Model model) {
    
        List<StateDropDownEntry> states = stateService.getStates();
        List<TownDropDownEntry> towns = townService.getTowns();
    
        ObjectMapper objMapper = new ObjectMapper();
        String statesJson = objMapper.writeValueAsString(states); // try|catch removed for clarity
        String townsJson = objMapper.writeValueAsString(towns);  
    
        model.addAttribute("statesJson",statesJson);
        model.addAttribute("townsJson",townsJson);
    
        return "stateTownQueryPage";
    }
    

    Although, I do acknowledge the alternate approach of architecting the materialization of those JSONs that are able to be created the first time the page is served as AJAX calls (just as you would those JSONs that depend on user input after the initial time the page is served) to controller methods which use the @ResponseBody annotation. That approach has its merits also.