JSON格式的字符串到字符串数组 [英] JSON formatted string to String Array

查看:241
本文介绍了JSON格式的字符串到字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用一个简单的PHP API(即我写的),返回一个JSON格式的字符串,如:

I'm using a simple php API (that I wrote) that returns a JSON formatted string such as:

[["Air Fortress","5639"],["Altered Beast","6091"],["American Gladiators","6024"],["Bases Loaded II: Second Season","5975"],["Battle Tank","5944"]]

我现在有一个包含JSON格式的字符串一个字符串,但需要将其转换成两个String数组,一个名字和一个ID。是否有任何快速路径实现这一点?

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?

推荐答案

您可以使用 org.json 库到你的JSON字符串转换为 JSONArray 然后你可以遍历。

You can use the org.json library to convert your json string to a JSONArray which you can then iterate over.

例如:

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]);

您甚至可以使用正则表达式来完成任务,虽然它的最好使用一个JSON库来解析JSON:

You can even use a regex to get the job done, although its much better to use a json library to parse 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));
}

这篇关于JSON格式的字符串到字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆