Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json String array into Java String list

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.

like image 496
Artemio Ramirez Avatar asked Apr 25 '16 16:04

Artemio Ramirez


3 Answers

For anyone else who might need this:

String jsonString = "[\"string1\",\"string2\",\"string3\"]";
ObjectMapper mapper = new ObjectMapper();
List<String> strings = mapper.readValue(jsonString, List.class);
like image 68
Artemio Ramirez Avatar answered Oct 03 '22 07:10

Artemio Ramirez


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");
like image 39
JvdB Avatar answered Oct 03 '22 05:10

JvdB


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);
}
like image 29
ryzhman Avatar answered Oct 03 '22 07:10

ryzhman