javajsonjspspring-mvcmodelandview

Spring MVC : Unable to get json value in jsp, it's giving 0


Need your help. I am not able to get json string in jsp after adding in modelAndView. After debugging, I found it's get added in modelAndView instace.

Below is the code snippet:

Controller:

modelAndView.addObject("json-data",jsonhelper.getJSONString(viewData));

JSP

<c:if test="${json-data != null}">

<script type="text/javascript">

     window.jsonData =${json-data};

 </script>

</c:if>

Here viewData is the object, that I need to get in jsp, but in jsp it's giving 0.


Solution

  • The dash (-) in json-data is being interpreted as the arithmetic operator minus.

    According to the spec (1.7.1):

    Binary operators - A {+,-,*} B

    If A and B are null, return (Long)0

    Therefore json-data is resolved to 0, json-data != null yields true, and window.jsonData is assigned the value 0.

    One solution is to rename your variable to jsonData or any other valid Java identifier.

    Alternatively, this will also work:

    window.jsonData = <%= request.getAttribute("json-data") %>