JSONArray getValue

时间:2015-10-03 08:05:10

标签: java json

我有一个包含以下内容的teams.json文件

{
"league": "Champions League",
"season": "2015/16",
"start": "2015-11-01",
"end": "2016-03-31",
"teams": [ 
    { "name": "Spain" },
    { "name": "Germany"},
    { "name": "Italy" },
    { "name": "Brasil" },
    { "name": "Argentina" }
]

}

我有JSONArray工作正常

    JSONObject jsonObject = (JSONObject) obj;
    JSONArray teamList = (JSONArray) jsonObject.get("teams");
    Iterator<JSONArray> iterator = teamList.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }

输出:

{"name":"Spain"}
{"name":"Germany"}
{"name":"Italy"}
{"name":"Brasil"}
{"name":"Argentina"}

但我只想要数组中没有{&#34; name&#34;:......的东西, 喜欢

西班牙,德国,意大利,巴西,阿根廷

3 个答案:

答案 0 :(得分:0)

你可以这样做:

package foo.bar;

import org.json.JSONArray;
import org.json.JSONObject;

public class JSON {

    public static void main(String[] args) {

        String str = "{\r\n\"league\": \"Champions League\",\r\n\"season\": \"2015/16\",\r\n\"start\": \"2015-11-01\",\r\n\"end\": \"2016-03-31\",\r\n\"teams\": [ \r\n    { \"name\": \"Spain\" },\r\n    { \"name\": \"Germany\"},\r\n    { \"name\": \"Italy\" },\r\n    { \"name\": \"Brasil\" },\r\n    { \"name\": \"Argentina\" }\r\n]}";
        JSONObject jsonObject = new JSONObject(str);
        JSONArray teamList = (JSONArray) jsonObject.get("teams");
        for (Object o : teamList) {
            JSONObject team = (JSONObject) o;
            System.out.println(team.getString("name"));
        }
    }
}

答案 1 :(得分:0)

我希望它能帮到你..!

 JSONArray teams=new JSONObject(jsondata).getJSONArray("teams");  
  for(int i=0;i<teams.length();i++){  
    JSONObject team=teams.getJSONObject(i);  
    System.out.println("value of name=="+team.getString("name"));  


}

答案 2 :(得分:0)

只需创建获取数组的辅助方法。

package com.example.helloworld;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class MyTest {
    public static void main(String[] args) throws JSONException {
        String str = "{'league': 'Champions League','season': '2015/16','start': '2015-11-01','end': '2016-03-31','teams': [ \r\n    { 'name': 'Spain' },\r\n    { 'name': 'Germany'},\r\n    { 'name': 'Italy' },\r\n    { 'name': 'Brasil' },\r\n    { 'name': 'Argentina' }\r\n]}";

        System.out.println(getCountyList(str).toString());
    }

    public static List<String> getCountyList(String json) throws JSONException {
        List<String> list = new ArrayList<String>();

        JSONObject jsonObject = new JSONObject(json);
        JSONArray teamList = (JSONArray) jsonObject.get("teams");
        for (int i = 0, len = teamList.length(); i < len; i++) {
            JSONObject team = (JSONObject) teamList.get(i);
            list.add((String) team.get("name"));
        }
        return list;
    }
}