Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/217.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java JSON格式的字符串到字符串数组_Java_Android_Json - Fatal编程技术网

Java JSON格式的字符串到字符串数组

Java JSON格式的字符串到字符串数组,java,android,json,Java,Android,Json,我正在使用一个简单的php API(我编写的),它返回一个JSON格式的字符串,例如: [["Air Fortress","5639"],["Altered Beast","6091"],["American Gladiators","6024"],["Bases Loaded II: Second Season","5975"],["Battle Tank","5944"]] 现在,我有一个包含JSON格式字符串的字符串,但需要将其转换为两个字符串数组,一个用于名称,一个用于id。有没有快速

我正在使用一个简单的php API(我编写的),它返回一个JSON格式的字符串,例如:

[["Air Fortress","5639"],["Altered Beast","6091"],["American Gladiators","6024"],["Bases Loaded II: Second Season","5975"],["Battle Tank","5944"]]
现在,我有一个包含JSON格式字符串的字符串,但需要将其转换为两个字符串数组,一个用于名称,一个用于id。有没有快速的方法可以实现这一点?

您可以使用该库将JSON字符串转换为一个
JSONArray
,然后可以对其进行迭代

例如:

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]);
String jsonString=“[[\“空中堡垒”、[\“5639\”]、[\“变身野兽”、[\“6091\”]、[\“美国角斗士”、\“6024\”]、[\“基地装载II:第二季”、“5975\”]、[\“战斗坦克”、“5944\”];
列表名称=新的ArrayList();
列表ID=新的ArrayList();
JSONArray数组=新的JSONArray(jsonString);
对于(int i=0;i
您甚至可以使用正则表达式来完成这项工作,尽管使用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));
}
List name=new ArrayList();
列表ID=新的ArrayList();
模式p=Pattern.compile(“\”(.*?\”,“\”(.*?\”);
匹配器m=匹配器p;
while(m.find()){
名称。添加(m.group(1));
id.add(m.group(2));
}

这一功能运行完美,无需使用或添加库。非常感谢。有很多解析器可供选择:啊!这不是JSON。da currley牙套在哪里。。。冒号呢?请注意,除非您实际发出正确的JSON,否则这些JSON库都不会工作。我会从那里开始…很有趣。我只是简单地使用php的json_encode函数来输出它。实际上,正确的json可能看起来更像:[{“名称”:“空中堡垒”,“id”:“5639”},{“名称”:“改变的野兽”,“id”:“6091”},{“名称”:“美国角斗士”,“id”:“6024”},{“名称”:“基地装载II:第二季”,“id”:“5975”},{“名称”:“战斗坦克”,“id”:“5944”}]