12

I have a webservice that returns a list of strings, only a list of strings:

["string1","string2","string3"]

How can I convert this into an ArrayList<String> in java? I'm trying to use jackson as I know you can convert Json to objects with it, but I can't find an example of a case like this.

2
  • You do not need a jackson for this Commented Apr 25, 2016 at 16:28
  • 2
    @sᴜʀᴇsʜᴀᴛᴛᴀ So, how would I do it natively then? Commented Apr 25, 2016 at 16:31

3 Answers 3

15

For anyone else who might need this:

String jsonString = "[\"string1\",\"string2\",\"string3\"]";
ObjectMapper mapper = new ObjectMapper();
List<String> strings = mapper.readValue(jsonString, List.class);
Sign up to request clarification or add additional context in comments.

1 Comment

This throws an unchecked exception warning FYI.
3

As ryzhman said, you are able to cast it to a List, but only of the object (JSONArray in ryzhman's case) extends the ArrayList class. You don't need an entire method for this. You can simply:

List<String> listOfStrings = new JSONArray(data);

Or if you are using IBM's JSONArray (com.ibm.json.java.JSONArray):

List<String> listOfStrings = (JSONArray) jsonObject.get("key");

Comments

1

It's weird, but there is a direct transformation from new JSONArray(stringWithJSONArray) into List. At least I was able to do like this:

public List<String> method(String data) {
    return new JSONArray(data);
}

Comments

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.