3

My JSP, is being passed an JSONObject in the context, on which it needs to do some processing like creating tables, etc.

But when I try to access the member of this object, it gives the following error - (the name of one of the keys in this object is ok)

 Servlet.service() for servlet jsp threw exception { javax.servlet.jsp.el.ELException:
 Unable to find a value for "ok" in object of class "org.json.JSONObject" using operator "."

JSP Code accessing it looks like this -

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<c:if test="${serviceOutput.ok}">
    <c:if test="${serviceOutput.ret.proposalCount} > 0">
.....

Can anyone please suggest how I can resolve this and successfully access all the members of this object?

kshtjsnghl
  • 591
  • 3
  • 8
  • 19

2 Answers2

2

The other option that could be taken now is to use a different JSON parsing library such as json-simple (http://code.google.com/p/json-simple/). The JSONObject in this library extends HashMap and the JSONArray extends an ArrayList, so EL should work with them. You would then not have to change your jstl or do extra parsing.

Pytry
  • 6,044
  • 2
  • 37
  • 56
1

EL only understands Javabeans and Maps. You need to let a preprocessing servlet convert each item of the JSONObject to a fullworthy Javabean which has getter methods which can be used in EL, or to a Map.

Here's an example which converts it to a Map:

Map<String, Object> serviceMap = new HashMap<String, Object>();
serviceMap.put("ok", serviceOutput.getBoolean("ok"));
serviceMap.put("foo", serviceOutput.getString("foo"));
// ...

request.setAttribute("serviceMap", serviceMap);
request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response);

This way EL expressions like ${serviceMap.ok} will work.

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Is there a way to read this JSON object without the EL, using some other way in jsp? – kshtjsnghl May 26 '11 at 18:11
  • Yes, using the old fashioned *scriptlets* which would totally break the MVC ideology. I'd rather solve it in the controller side than in the view side. – BalusC May 26 '11 at 18:12