0

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.

P.S. I have response in a string object.

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

Thanking in anticipation.

1
  • It'd amazing to know why I got a neg vote? I'd try to avoid that in future. Commented Jan 3, 2013 at 20:56

2 Answers 2

2

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.

1
  • @Umayr: I've added links to the manual; there are some examples there. Commented Jan 3, 2013 at 20:44
1

Take a loot at java.util.Arrays.

List<String> list = Arrays.asList(["Item1", "Item2", "Item3"]);
2
  • Would it work for "["Item1", "Item2", "Item3"]" too? as I have all results in a String Object. I added my code, that might help to elaborate my objective. Commented Jan 3, 2013 at 20:46
  • Nope, but you could make a single String into a String[]. Take a look at .split() method in the String class. I believe that without any arguments passed in the method will spit a string based on the 'space' character so each item would be their own index in the array. Since the string is formated in JSON syntax, you could try using regex, StringTokenizer, or search around for a apache-commons or guava for a utility that could handle the split for you or cop-out and try looking at the JSON class to see if can cleanly parse out the text. Commented Jan 3, 2013 at 21:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.