开发者

Creating a JSON response from Google Application Engine

Purely as an academic exercise I wanted to convert one of my existing GAE applets to return the response back to Android in JSON and parse it accordingly.

The original XML response containing a series of booleans was returned thus:

StringBuilder response = new StringBuilder();
    response.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
    response.append("<friend-response><added>");
    response.append(friendAdded);
    response.append("</added><removed>");
    response.append(friendRemoved);
    response.append("</removed><found>");
    response.append(friendFound);
    response.append("</found></friend-response>");

I want to replace this with a JSON response that looks something like this:

{ "friendResponse" : [ { "added":true, "removed":false, "found":true } ]}

I think I can generate the array contents as follows (I haven't tested it yet) but I don't know how to create t开发者_JAVA百科he top-level friendResponse array itself. I can't seem to find any good examples of creating JSON responses in Java using the com.google.appengine.repackaged.org.json library. Can anyone help put me on the right path?

boolean friendAdded, friendRemoved, friendFound;
/* Omitted the code that sets the above for clarity */
HttpServletResponse resp;
resp.setContentType("application/json");
resp.setHeader("Cache-Control", "no-cache");

JSONObject json = new JSONObject();
try {
    //How do I create this as part of a friendResponse array?
    json.put("added", friendAdded);
    json.put("removed", friendRemoved);
    json.put("found", friendFound);
    json.write(resp.getWriter());
} catch (JSONException e) {
    System.err
    .println("Failed to create JSON response: " + e.getMessage());
}


You need to use JSONArray to create the (single-element) array that will store your object:

try {
    JSONObject friendResponse = new JSONObject();
    friendResponse.put("added", friendAdded);
    friendResponse.put("removed", friendRemoved);
    friendResponse.put("found", friendFound);

    JSONArray friendResponseArray = new JSONArray();
    friendResponseArray.put(friendResponse);

    JSONObject json = new JSONObject();
    json.put("friendResponse", friendResponseArray);
    json.write(resp.getWriter());
} catch (JSONException e) {
    System.err
    .println("Failed to create JSON response: " + e.getMessage());
}


You can use GSON: https://sites.google.com/site/gson/gson-user-guide#TOC-Object-Examples

With this framework, you can serialize an object to json, and vice versa.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜