java JSON 格式的字符串到字符串数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4819405/
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 formatted string to String Array
提问by madzilla
I'm using a simple php API (that I wrote) that returns a JSON formatted string such as:
我正在使用一个简单的 php API(我写的),它返回一个 JSON 格式的字符串,例如:
[["Air Fortress","5639"],["Altered Beast","6091"],["American Gladiators","6024"],["Bases Loaded II: Second Season","5975"],["Battle Tank","5944"]]
I now have a String that contains the JSON formatted string but need to convert it into two String arrays, one for name and one for id. Are there any quick paths to accomplishing this?
我现在有一个包含 JSON 格式字符串的字符串,但需要将其转换为两个字符串数组,一个用于名称,另一个用于 id。是否有任何快速途径来实现这一目标?
回答by dogbane
You can use the org.jsonlibrary to convert your json string to a JSONArray
which you can then iterate over.
您可以使用org.json库将您的 json 字符串转换为 a JSONArray
,然后您可以对其进行迭代。
For example:
例如:
String jsonString = "[[\"Air Fortress\",\"5639\"],[\"Altered Beast\",\"6091\"],[\"American Gladiators\",\"6024\"],[\"Bases Loaded II: Second Season\",\"5975\"],[\"Battle Tank\",\"5944\"]]";
List<String> names = new ArrayList<String>();
List<String> ids = new ArrayList<String>();
JSONArray array = new JSONArray(jsonString);
for(int i = 0 ; i < array.length(); i++){
JSONArray subArray = (JSONArray)array.get(i);
String name = (String)subArray.get(0);
names.add(name);
String id = (String)subArray.get(1);
ids.add(id);
}
//to convert the lists to arrays
String[] nameArray = names.toArray(new String[0]);
String[] idArray = ids.toArray(new String[0]);
You can even use a regex to get the job done, although its much better to use a json library to parse json:
您甚至可以使用正则表达式来完成工作,尽管使用 json 库来解析 json 会更好:
List<String> names = new ArrayList<String>();
List<String> ids = new ArrayList<String>();
Pattern p = Pattern.compile("\"(.*?)\",\"(.*?)\"") ;
Matcher m = p.matcher(s);
while(m.find()){
names.add(m.group(1));
ids.add(m.group(2));
}