0

我正在从我的 Java 应用程序调用 RESTful Api,它为我提供以下格式的结果:

["Item1", "Item2" , "Item3"]

如何将其解析为 ArrayList 对象?

代码:

    private String getResponseString(URI URL) {

    HttpClient client = new DefaultHttpClient();
    HttpContext context = new BasicHttpContext();
    HttpGet get = new HttpGet();
    get.setURI(URL);

    try {
        HttpResponse response = client.execute(get, context);
        return getASCIIContentFromEntity(response.getEntity());

    } catch (ClientProtocolException e) {
        Log.e(Static.DebugTag, e.getMessage());
        return null;
    } catch (IOException e) {
        Log.e(Static.DebugTag, e.getMessage());
        return null;
    }

}

private String getASCIIContentFromEntity(HttpEntity entity)
        throws IllegalStateException, IOException {
    InputStream in = entity.getContent();
    StringBuffer out = new StringBuffer();
    int n = 1;
    while (n > 0) {
        byte[] b = new byte[4096];
        n = in.read(b);
        if (n > 0)
            out.append(new String(b, 0, n));
    }
    return out.toString();
}

现在我想创建另一个函数,它以字符串返回形式 getASCIIContentFromEntity() 作为参数并返回一个 Arraylist。

PS我在一个字符串对象中有响应。

PPS 标题可能会产生误导,因为我不知道该怎么称呼它。

期待中的感谢。

4

2 回答 2

2

由于字符串似乎包含有效的JSON,因此您可以使用 JSON 解析器(例如Gson)来解析字符串。请参阅手册中的数组示例集合示例

于 2013-01-03T20:40:47.333 回答
1

在 java.util.Arrays 中掠夺。

List<String> list = Arrays.asList(["Item1", "Item2", "Item3"]);
于 2013-01-03T20:42:54.990 回答