【问题标题】:read JSON array in servlet with json_simple使用 json_simple 在 servlet 中读取 JSON 数组
【发布时间】:2013-12-20 21:51:00
【问题描述】:

我在我的 android 代码中创建了一个 JSON 数组并将其发布到我的 servlet,如下所示:

JSONArray Data = new JSONArray();

for (i = 0; i <= 10; i++) {
Data.put(String.valueOf(i));
}
}

URI url = new URI(serveraddress);
HttpPost httpPost = new HttpPost(url);
StringEntity DataEntity = new StringEntity(Data.toString());
DataEntity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
httpPost.setEntity(DataEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);

然后在我的 servlet 中,我使用阅读器从 http 请求中获取内容,如下所示:

StringBuffer jb = new StringBuffer();
String line = null;
try {
BufferedReader reader = req.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
} catch (Exception e) { /*report an error*/ }

现在我不确定如何从这个字符串创建 JSON 数组。 servlet 托管在带有 json_simple 库的 jetty Web 服务器中。 JSONArray 类只有一个空的构造函数,这与 Android 包中的构造函数不同,后者也有一个带有字符串参数的构造函数。那么有人可以给我一个关于如何从字符串创建 JSON 数组的提示吗?

【问题讨论】:

    标签: android json servlets


    【解决方案1】:

    试试这个代码:

    JsonParser parser = new JsonParser();
    JsonElement element = (JsonElement) parser.parse(line); 
    JsonArray array = element.getAsJsonArray();
    

    希望对你有帮助。

    【讨论】:

    • JsonElement 无法解析为类型。那是在哪个包裹里?你指的是gson吗?我正在使用 json_simple
    • @George-Brighton 感谢您将 JSONParser 格式化回 JsonParser。我无意中在我的代码中使用了 org.json.simple.parser.JSONParser 而不是 com.google.gson.JsonParser 并且它崩溃了。你帮我省了很多麻烦:)
    【解决方案2】:

    试试看

    String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
    
                out = sb.toString();
            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            }
    
    
    try {
                jObj = new JSONObject(out );
            } catch (JSONException e) {
                jObj = new JSONObject();
                try {
                    JSONArray ja = new JSONArray(json);
                    jObj.put("array",ja);
                } catch (JSONException e1) {
                    // TODO Auto-generated catch block
                    Log.e("JSON Parser", "Error parsing data " + e1.toString());
                }
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }
    

    【讨论】:

    • 您还必须参考 gson 库,因为 json_simple 没有 JSONArray(JSONObject) 构造函数。谢谢,试试看。
    猜你喜欢
    • 2016-04-19
    • 1970-01-01
    • 2013-09-13
    • 2020-01-27
    • 2013-07-22
    • 2011-07-17
    • 1970-01-01
    • 2014-10-17
    • 2016-06-27
    相关资源
    最近更新 更多