0

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; 

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

That was my initial thought. Wasnt sure if it was the correct approach. As with API calls the RequestMappingHandlerAdapter would serialize the json somehow.
@user2524908 One alternative is to produce a HTML page with Javascript which sends a request to a different API that retrieves JSON directly.
Thanks for the help. I also enjoy scala!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.