passing data from a servlet to javascript code in an Ajax application?


This question already has an answer here:


The best way is using JSON. There are several Java libraries which can convert fullworthy Java objects to a JSON string and vice versa. Further JSON can be accessed in Javascript in a fully natural way without converting/massaging the data forth and back in another format.

As to the server side part, I strongly recommend to pick Google Gson as JSON serializer. Gson is the preferred choice since it supports converting complex Javabeans and arrays, collections and maps of them to JSON and vice versa without pains in a single line of code. It even supports generics. Basically all you need to do is the following:

String json = new Gson().toJson(object);

Check the user guide to learn more about the powers of Gson.

All with all, the following in the server side is sufficient:

public static void writeJson(HttpServletResponse response, Object object) throws IOException {
    response.getWriter().write(new Gson().toJson(object));

Need Your Help

How to Hash Submitted passwords using JdbcRealm in Shiro?

shiro jdbcrealm

I've created an application and been using Shiro for the authentication.

Cocos2D: kazmath/kazmath.h file not found

file path header cocos2d-iphone

I am upgrading Cocos2D 0.99.5 to version 2. I was hoping the other Stack Overflow questions about this would help me but they have not.