user2524908
user2524908

Reputation: 871

Java Spring serialize json to view

Looking to output a json object on a JSP view within JAVA Spring. However when I perform the following all I see is the java object toString()

@RequestMapping(value = "/home", method = RequestMethod.GET)                                     
@ResponseBody                                                                                    
public ModelAndView homePage() {                                                                 
    MapDAOImpl mapDAOImpl = (MapDAOImpl) appContext.getBean("mapDAOImpl");                       
    ReturnLocations[] daoResponse  = mapDAOImpl.getPropertiesJsFilter(params);           



    ModelAndView model = new ModelAndView();                                                     
    model.setViewName("home");                                                                   
    model.addObject("locations", daoResponse);                                                   
    return model;                                                                                
}                                                                                                

JSP

<script>
<c:out value="${locations}" />
</script>                                                                              

edit solution:

 ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();       
 String json = ow.writeValueAsString(daoResponse);                               
 ModelAndView model = new ModelAndView();                                        
 model.setViewName("home");                                                      

 model.addObject("locations", json);                                             
 return model; 

Upvotes: 0

Views: 464

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280000

Just serialize the ReturnLocations[] to JSON inside your handler method, store the result in a String and add that String to the Model. You'll have access to it in the JSP through request attributes.

An alternative is to render an HTML page with Javascript which sends a request to a separate API which then returns the JSON directly (serialized with @ResponseBody for example). You can then do whatever you want with that result.

Upvotes: 1

Related Questions