2

I have an Ajax call in my JSP which returns a JSON object in the form of Java string.

public void doGet(HttpServletRequest request, HttpServletResponse res) throws IOException, ServletException {
    try {
        String fromDate = request.getParameter("drFrom");
        String toDate = request.getParameter("drTo");
        JSONArray jsonArray = chartData.getCCSBJson(fromDate, toDate);
        res.setContentType("application/json");
        res.getWriter().write(jsonArray.toString());

Can I send the JSON to JSP without using jsonArray.toString() inside res.getWriter().write(jsonArray.toString());, because I am not able to parse the JSON in JSP after sending it as a string.

This is related to the post: How to parse a JSON object from ajax call in Java Script

2
  • There should be no problem when converting a JSONXxx object to String because that's the real JSON format. The problem is in your JSONArray. Post the code for chartData.getCCSBJson(fromDate, toDate). Or maybe the problem is in JSP side. Post how you're parsing the String in your client. Commented Jun 4, 2014 at 16:05
  • possible duplicate of How to parse a JSON object from ajax call in Java Script Commented Jun 4, 2014 at 22:46

1 Answer 1

3

Simply parse the JSON string into Java object in Servlet itself and pass the Java Object to the JSP instead of plain String.

Steps to follow:

  • Simply create a Java POJO class that is replica of JSON string
  • Convert the JSON string into POJO class object in the Servlet itself
  • Set the object in HTTP request as an attribute
  • Get the object back from HTTP request in JSP

Note: Java POJO class must be Serializable.

Try with JavaScript - JSON.parse() method that parses a string as JSON, optionally transforming the value produced by parsing in JavaScript.

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

Comments

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.