【问题标题】:JSON formatted string to String ArrayJSON 格式的字符串到字符串数组
【发布时间】:2011-01-27 17:00:31
【问题描述】:

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

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

我现在有一个包含 JSON 格式字符串的字符串,但需要将其转换为两个字符串数组,一个用于名称,一个用于 id。有没有什么快捷的方法可以做到这一点?

【问题讨论】:

  • 啊!这不是 JSON。大花括号在哪里? ...和冒号?
  • 郑重声明,除非您真正发出正确的 JSON,否则这些 JSON 库都不会工作。我会从那里开始......
  • 有趣。我只是使用 php 的 json_encode 函数来输出这个。
  • 实际上,正确的 JSON 可能看起来更像:[{"name":"Air Fortress","id":"5639"},{"name":"Altered Beast","id ":"6091"},{"name":"American Gladiators","id":"6024"},{"name":"Bases Loaded II: Second Season","id":"5975"},{ "name":"主战坦克","id":"5944"}]

标签: java android json


【解决方案1】:

您可以使用org.json 库将您的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]);

您甚至可以使用正则表达式来完成工作,尽管使用 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));
}

【讨论】:

  • 这工作完美,无需使用或额外的库。谢谢!
猜你喜欢
  • 2021-09-25
  • 1970-01-01
  • 1970-01-01
  • 2013-04-27
  • 1970-01-01
  • 2018-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多