【问题标题】:Creating a JSON response from Google Application Engine从 Google 应用程序引擎创建 JSON 响应
【发布时间】:2011-09-23 12:02:02
【问题描述】:

纯粹作为一项学术练习,我想将我现有的一个 GAE 小程序转换为以 JSON 格式将响应返回给 Android 并进行相应的解析。

返回包含一系列布尔值的原始 XML 响应:

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>");

我想用如下所示的 JSON 响应替换它:

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

我想我可以按如下方式生成数组内容(我还没有测试过),但我不知道如何创建顶级friendResponse数组本身。我似乎找不到任何使用 com.google.appengine.repackaged.org.json 库在 Java 中创建 JSON 响应的好例子。谁能帮助我走上正确的道路?

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());
}

【问题讨论】:

    标签: android json google-app-engine


    【解决方案1】:

    您需要使用JSONArray 创建将存储您的对象的(单元素)数组:

    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());
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用 GSON:https://sites.google.com/site/gson/gson-user-guide#TOC-Object-Examples

      有了这个框架,你可以将一个对象序列化为json,反之亦然。

      【讨论】:

        猜你喜欢
        • 2010-09-26
        • 1970-01-01
        • 1970-01-01
        • 2016-07-04
        • 2019-11-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-02
        相关资源
        最近更新 更多