简体   繁体   中英

How to send JSON array from server to client, i.e. (java to AJAX/Javascript)?

I have the following JSON array in my JSON.java file:

ArrayList array=new ArrayList();
array.add("D");
array.add("A");
array.add("L");

I would like to send array to the AJAX script located in AJAX.jsp. I know how to receive the text in AJAX via eg

document.getElementById("txtHint").innerHTML=xmlhttp.responseText;

But I don't know how to send the array from the server to the client! Appreciate your help

you basically use certain classes in java like the ones defined here: http://json.org/java/ convert the final output to a json string and then send it to javascript there you convert the json string back to json using eval or probably using a library called json2.js and you are all set..

here is code for the same:

JSONObject obj=new JSONObject();
  obj.put("name","foo");
  obj.put("num",new Integer(100));
  obj.put("balance",new Double(1000.21));
  obj.put("is_vip",new Boolean(true));
  obj.put("nickname",null);
  StringWriter out = new StringWriter();
  obj.writeJSONString(out);
  String jsonText = out.toString();
  System.out.print(jsonText);

for more http://code.google.com/p/json-simple/wiki/EncodingExamples

ok First:

ArrayList array=new ArrayList();
array.add("D");
array.add("A");
array.add("L");
JSONArray array = new JSONArray();

This can't compile... you have a duplicate variable array;-)

Second: create a servlet/Struts Action/etc that will contains the code that will create your array. Then transform it in JSON with a JSON library. Finally, put the string in the response of your servlet/Struts Action/etc.

Use JQuery to ease your effort on the Ajax call. It will help you with the Ajax call and the transformation back to Json from the string received in the http response.

Ex:

your ajax call should be like that (with JQuery)

$.getJSON("http://yourserver/JSONServlet",
    function(data){
           alert (data) // this will show your actual json array
      });
    });

and your servlet should look like that:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import net.sf.json.JSONArray;

public class JSONServlet extends  HttpServlet{
  public void doGet(HttpServletRequest request,
  HttpServletResponse response)
   throws ServletException,IOException{
 JSONArray arrayObj=new JSONArray();
 arrayObj.add("D");
 arrayObj.add("A");
 arrayObj.add("L");
 arrayObj.add("D");
 arrayObj.add("A");
 arrayObj.add("TEST");
  PrintWriter out = response.getWriter();
  out.println(arrayObj);
  for(int i=0;i<arrayObj.size();i++){
  out.println(arrayObj.getString(i));
  }
 }
}

Instead of using org.json's barebones library as suggested already, consider using data-binding JSON library like Jackson or GSON (there are many others as well), in which case you can simplify servlet case (with Jackson) to:

new ObjectMapper().writeValue(response.getOutputStream(), array);

and that's all you need.

And for even simpler handling, JAX-RS services (Jersey, RESTeasy, CXF) can further simplify handling, to reduce code you need compared to raw servlets. JAX-RS + JSON is the modern way to implement web services on Java, so might make sense to learn it now.

The simplest way is construct a json string in java file and return that json string to client.

Javascript provides a eval() method which inverts json string to json object.

Then you can perform what ever operations you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM