What library should i use to accomplish that?
Have a look at json-simple.
How to convert from list of java objects to list of JSON objects?
If you decide to use json-simple, have a look at the encoding examples.
How to access this list of JSON objects in a javascript function?
For this, you can either output it on the page (as a JavaScript var = [...]
statement) or pull it in via AJAX. If you decide on the latter, you can decode it using JSON2.js.
If you're using an AJAX library of some sort, it's highly likely your library can decode JSON already. For example: jQuery.parseJSON and YUI.JSON.
Edit: Here's some example code:
As is mentioned in the encoding examples (here), your class User
will need to implement JSONAware
and provide a toJSONString
method:
class User implements JSONAware {
private int id;
private String name;
private String email;
public User(int id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}
public String toJSONString() {
StringBuffer sb = new StringBuffer();
sb.append("{");
sb.append(JSONObject.escape("id"));
sb.append(":");
sb.append("\"" + JSONObject.escape(this.id) + "\"");
sb.append(",");
sb.append(JSONObject.escape("name"));
sb.append(":");
sb.append("\"" + JSONObject.escape(this.name) + "\"");
sb.append(",");
sb.append(JSONObject.escape("email"));
sb.append(":");
sb.append("\"" + JSONObject.escape(this.email) + "\"");
sb.append("}");
return sb.toString();
}
}
Now, to convert your List
of User
s to JSON, simply use:
String jsonText = JSONValue.toJSONString(users);
I leave it up to you to figure out how to get this string into your JavaScript, either by print
ing it into a <script>
tag in your HTML or via AJAX (an decoding it with e.g. JSON2.js).