简体   繁体   中英

Parsing String Array into Arraylist in Java

I'm calling a RESTful Api from my Java application which provides me result in following format:

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

How do I parse it into ArrayList object?

Code:

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

Now I want to make another function that takes the String returning form getASCIIContentFromEntity() as param and return an Arraylist.

PS I have response in a string object.

PPS Title may be misleading as in I don't have idea what to call it.

Thanking in anticipation.

Since the string appears to contain valid JSON , you could use a JSON parser, such as Gson , to parse the string. See Arrays Examples and Collections Examples in the manual.

抢劫java.util.Arrays。

List<String> list = Arrays.asList(["Item1", "Item2", "Item3"]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM