Json 字符串数组转换成 Java 字符串列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36846055/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Json String array into Java String list
提问by Artemio Ramirez
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 Hymanson as I know you can convert Json to objects with it, but I can't find an example of a case like this.
如何将其转换为ArrayList<String>
Java 中的一个?我正在尝试使用 Hymanson,因为我知道你可以用它将 Json 转换为对象,但我找不到这样的例子。
采纳答案by Artemio Ramirez
For anyone else who might need this:
对于可能需要此功能的任何其他人:
String jsonString = "[\"string1\",\"string2\",\"string3\"]";
ObjectMapper mapper = new ObjectMapper();
List<String> strings = mapper.readValue(jsonString, List.class);
回答by JvdB
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:
正如 ryzhman 所说,您可以将其转换为 List,但只有对象(在 ryzhman 的情况下为 JSONArray)扩展了 ArrayList 类。你不需要一个完整的方法。您可以简单地:
List<String> listOfStrings = new JSONArray(data);
Or if you are using IBM's JSONArray (com.ibm.json.java.JSONArray):
或者,如果您使用 IBM 的 JSONArray (com.ibm.json.java.JSONArray):
List<String> listOfStrings = (JSONArray) jsonObject.get("key");
回答by ryzhman
It's weird, but there is a direct transformation from new JSONArray(stringWithJSONArray) into List. At least I was able to do like this:
这很奇怪,但是有一个从 new JSONArray(stringWithJSONArray) 到 List 的直接转换。至少我能够这样做:
public List<String> method(String data) {
return new JSONArray(data);
}