Use Json Object as Spring MVC view model directly without converting it to Java object

195 views Asked by At

I am working on a spring MVC project and currently making a new API call to a backend service to get response and use it as the viewModel of Spring MVC ModelAndView.

However, unlike traditional flow, this time I dont' want to convert the json object as java POJO object first. Instead, I want to use the json object as the viewModel of the ModelAndView directly. Meanwhile, I also want to access the json object naturally in jsp as if I am accessing the java POJO object. Is this possible?

@RequestMapping(value = {SOME_VALUE})
public ModelAndView myFunction() {
  ModelAndView modelAndView = new ModelAndView("myViewName");
  //getAPIResponseASJsonObject() return json object, with frameworks, I can convert it to Gson JsonObject, or org.json JSONObject
  modelAndView.addObject("viewModel", getAPIResponseASJsonObject());
  
...
  return modelAndView

}

I know in jsp I can access json object with EL. But I need use some "escape" mechanism if I want to combine it with standard JSTL taglib.

// if I have a Json object "Person" as viewModel like below in jsp:

{
  "name": "john",
  "age": 30
}


// then in jsp file if I want to access the name property, I need to write jsp like this:

${Person.get("name")}

//or
<c:set var="name" value="${Person.get(\"name\")}">

This looks unnatural compared with using Java POJO viewModel. And the jsp may be hard to maintain if the json object is complicated.

With Java POJO, I can easily write

//Person POJO
public Class Person{
 private String name;
 private int age;

//getter and setter

}


<c:set var="name" value="${Person.name}">

to access the name attribute.

Possible solutions I think maybe:

  1. Assuming I am using Google Gson, I can try to create JsonObjectBean, JsonArrayBean, JsonPrimitiveBean which extend JsonElement abstract class so that I "magically" convert the json object java class to java bean.
  2. Write dedicated JSP tags to avoid using escape.
0

There are 0 answers