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.
For anyone else who might need this:
String jsonString = "[\"string1\",\"string2\",\"string3\"]";
ObjectMapper mapper = new ObjectMapper();
List<String> strings = mapper.readValue(jsonString, List.class);
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");
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With