Android json数组:我如何得到和具体的字符串?

时间:2016-06-29 21:53:26

标签: android arrays json

我有一个Json脚本,可以从Mysql数据库中获取数据并将其打印在不同的TextViews中。我想知道的是我如何才能仅举出“idE”值并将其打印在“TextViewTitulo”TextView

try {
String response = "[{"0":"1","id":"1","1":"f3n","idE":"f3n","2":"bar","tipo":"bar"},{"0":"1","id":"1","1":"f3n","idE":"f3n","2":"bar2","tipo":"bar2"}]"
JSONArray array;
array = new JSONArray(response);


StringBuilder sb = new StringBuilder();
for (i=0; i<array.length(); i++) {
    // chain each string, separated with a new line
    sb.append(array.getString(i) + "\n");
}
// display the content on textview
textViewTitulo.setText(sb.toString());

} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

我的代码工作正常,但显示整个字符串

2 个答案:

答案 0 :(得分:0)

当然你可以得到它,你只需要遍历整个JSONArray。如果你知道你正在寻找的价值,你必须搜索它,如果你知道索引 - 它更容易,你只需要得到它。因此,对于第一种情况,您可以执行以下操作:

for (int i = 0; i < array.length(); i++) {
  JSONObject current = array.getJSONObject(i);
  // In your case the JSONObject is more complicated
  // so you need to iterate over it too
  Iterator<?> keys = current.keys();

  while(keys.hasNext()) {
      String key = (String)keys.next();
      String value = current.get(key);
      // Do something with the value
  }

  // Or If you know what key you are looking for, you may do
  String value = current.get("idE");
  // Do something with value
}

答案 1 :(得分:0)

您的JSONArray中有2个对象,1个textview用于显示数据,因此我添加追加​​" "来分隔它们。

 for (i=0; i<array.length(); i++) {
        sb.append(array.getJSONObject(i).getString("idE"));
        sb.append(" ");
        //do whatever with it
    }
 textViewTitulo.setText(sb.toString());