使用json_simple读取servlet中的JSON数组

时间:2013-12-04 12:03:18

标签: android json servlets

我在我的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数组的提示吗?

2 个答案:

答案 0 :(得分:0)

试试这段代码:

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

希望它有所帮助。

答案 1 :(得分:0)

试试吧

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