Reputation: 1136
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.
Upvotes: 11
Views: 32686
Reputation: 49
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");
Upvotes: 2
Reputation: 674
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);
}
Upvotes: 1
Reputation: 1136
For anyone else who might need this:
String jsonString = "[\"string1\",\"string2\",\"string3\"]";
ObjectMapper mapper = new ObjectMapper();
List<String> strings = mapper.readValue(jsonString, List.class);
Upvotes: 13