我如何在Java中解析这些元素

时间:2014-07-07 23:02:14

标签: java android arrays json object

我在解析这些元素方面遇到了一些麻烦

[
    {"inicio":"11:15:00","dia":"04\/07\/2014","local":"R. Domingos Cristal, 1-103 - ジャルジン・アンジェラ - São Paulo","fim":"18:45:00"},
    {"inicio":"11:15:00","dia":"06\/07\/2014","local":"R. Domingos Cristal, 103 - ジャルジン・アンジェラ - São Paulo","fim":"19:45:00"},    
    {"inicio":"11:15:00","dia":"05\/07\/2014","local":"R. Domingos Cristal, 103 - ジャルジン・アンジェラ - São Paulo","fim":"19:45:00"}, 
    {"inicio":"11:15:00","dia":"04\/07\/2014","local":"R. Domingos Cristal, 103 - ジャルジン・アンジェラ - São Paulo","fim":"19:45:00"}, 
    {"inicio":"11:15:00","dia":"06\/07\/2014","local":"R. Domingos Cristal, 1-103 - ジャルジン・アンジェラ - São Paulo","fim":"19:45:00"}, 
    {"inicio":"11:15:00","dia":"05\/07\/2014","local":"R. Domingos Cristal, 1-103 - ジャルジン・アンジェラ - São Paulo","fim":"19:45:00"}
]

我希望从每个对象中获取每个值,例如" local"从第二个数组。我尝试过转换为字符串,但没有用。也许这个问题出现在第一个解析中,我不知道。

这是我的回答:

spots = json.getJSONArray("spots");
int length = spots.length();
            List<Object> listContents = new ArrayList<Object>(length);

            for (int i=0; i<length; i++) {
                try {
                    listContents.add(spots.getString(i));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            SpotsFragment.returnSpots(listContents, parent);

我试过这个:

public static void returnSpots(List<Object> listContents, Activity act) {

    System.out.println(listContents);
    ListView lv = (ListView) act.findViewById(R.id.listView);
    lv.setAdapter(new ArrayAdapter<String>(act,android.R.layout.simple_list_item_1, listContents));
}

但是它将对象块添加为字符串,我无法访问每个值。

1 个答案:

答案 0 :(得分:0)

我的解决方案: 响应:

int length = spots.length();
            List<Object> listContents = new ArrayList<Object>   (length);
            for (int i = 0; i < length; i++) {
                try {
                    listContents.add(spots.get(i));
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
            SpotsFragment.returnSpots(listContents, parent);

返回:

ArrayList<String> listObject = new ArrayList<String>();
    for (Object listContent : listContents) {
        JSONObject obj = (JSONObject) listContent;
        String inicio = obj.optString("inicio");
        String dia = obj.optString("dia");
        String local = obj.optString("local");
        String fim = obj.optString("fim");
        listObject.add(inicio);
        listObject.add(dia);
        listObject.add(local);
        listObject.add(fim);
    }
    ListView lv = (ListView) act.findViewById(R.id.listView);
    lv.setAdapter(new ArrayAdapter<String>(act, android.R.layout.simple_list_item_1, listObject));