Sunday, April 29, 2007

JSON speed up Ajax

The JavaScript Object Notation, or JSON, is a lightweight syntax for representing data. JSON has structure with nesting of data elements, just as XML does. JSON is also text-based and use Unicode. It is just as readable by humans as XML is. Here comes a simple example for Json:
{"totalCount":2,
"results":[{"bh":"100","sm":"hello"},{"bh":"101","sm":"me" }]}
The big different about JSON and XML is that JSON is a subset of JavaScript. I can use JavaScript's own compiler to do just that by calling eval. Parsing JSON is a one-liner! Moreover, navigating an object synthesized from JSON is identical to navigating any JavaScript object. It's far easier than navigating through the DOM tree.

To create a JSON object in server side with Java. We can use the lib in "json.org". It provides a quick API to parse POJO and list etc. See the following example code:
public JSONObject toJSONObject() throws Exception {
JSONObject json = new JSONObject();
json.put("totalCount", totalCount);

JSONArray jsonItems = new JSONArray();
for (Iterator iter = results.iterator(); iter.hasNext();) {
jsonItems.put(iter.next().toJSONObject());
}
json.put("results", jsonItems);

return json;
}
To parse JSON data from JS in serve side, please see the following example:
JSONArray jsonArray = JsonUtil.getJsonArray(jsonString);
// JsonUtil.getJsonArray(jsonString) just do this ->
// jsonArray = new JSONArray(jsonString);

// loop through - get from json and update
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String id = jsonObject.getString("id");
}

2 comments:

Unknown said...

Hello there,
I was wondering if you have the code for JsonUtil.getJsonArray(jsonString)...I mean this class? I have not been able to find anything.
right now I am parsing the String into an object and converting the same to JSONArray. I know only two lines, but this class that you have used would give me better results.
Thanks,
Manju

ffzhuang said...

Hi, Manju:

Would you please give me your email address. My email is: ffzhuang@gmail.com