【问题标题】:Add JSONObject in the for loop to the JSONObject outside将for循环中的JSONObject添加到外面的JSONObject中
【发布时间】:2015-06-11 12:55:39
【问题描述】:

我正在尝试将所有 JSONobject arrivals 添加到外部的 for 循环 JSONobject stops 中,但我总是在 stops 中得到一个 JSONObject。如何将所有arrivales JSONObject 放在 JSONObject stops 的 for 循环中?

我正在使用 json 库 org.json。

感谢您的帮助

  JSONObject stops = new JSONObject(); 

    for (Entry<String, List<String>> entry : map.entrySet()) {
        String key = entry.getKey();
        List<String> timeEntries = entry.getValue();                        
        try {                       
        stops.put("stops_name", key);

        JSONObject arrivals = new JSONObject();
        JSONArray arrivalMoFr  = new JSONArray();

        JSONArray timeArray = new JSONArray(timeEntries);
        arrivalMoFr.put( timeArray);

        arrivals.put("mon-fri", arrivalMoFr);

        stops.put("arrival_time", arrivals);

        System.out.println(stops.toString(3));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

【问题讨论】:

    标签: java json


    【解决方案1】:

    在循环外声明对象并在循环中继续添加项目。每次循环运行时都会实例化您的到达和到达MoFr,并且您会获得最后一个项目。试试这个

       JSONObject stops = new JSONObject(); 
       JSONObject arrivals = new JSONObject();
       JSONArray arrivalMoFr  = new JSONArray();
    
    for (Entry<String, List<String>> entry : map.entrySet()) {
        String key = entry.getKey();
        List<String> timeEntries = entry.getValue();                        
        try {                       
             stops.put("stops_name", key);
    
    
    
             JSONArray timeArray = new JSONArray(timeEntries);
             arrivalMoFr.put( timeArray);
    
             arrivals.put("mon-fri", arrivalMoFr);
    
             stops.put("arrival_time", arrivals);
    
             System.out.println(stops.toString(3));
        } catch (JSONException e) {
             e.printStackTrace();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-08-21
      • 1970-01-01
      • 2021-05-09
      • 1970-01-01
      • 2021-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多