使用 java-json 连接 JSON 个元素

Concatinating JSON elements using java-json

我有一个程序读取 CSV 文件和 returns JSON String.

但是使用 JsonArray and JsonObject 只会产生文件的最后一行结果。如何将多行数据连接到一个 JSON 对象中?

输出

[{"name":"Other_Renwables","load":"14.3"},{"name":"Other_Renwables","load":"14.3"},{"name":"Other_Renwables","load":"14.3"},{"name":"Other_Renwables","load":"14.3"},{"name":"Other_Renwables","load":"14.3"},{"name":"Other_Renwables","load":"14.3"}]

代码

JSONObject jObject = new JSONObject();
        JSONArray jArray = new JSONArray();
        int count = 0;

         try{  
             logger.info("\nSending 'GET' request to URL : " + url);
             HttpGet httpGet = new HttpGet(url);
             HttpResponse response = httpClient.execute(httpGet);
             int responseCode = response.getStatusLine().getStatusCode();
             logger.info("Response Code : " + responseCode);
             if (responseCode != 404){
                 try(BufferedReader reader = new BufferedReader(
                        new InputStreamReader(
                                response.getEntity().getContent()))) {
                     if(reader != null){
                         //StringBuilder builder = new StringBuilder();
                         String aux = "";
                         while ((aux = reader.readLine()) != null) {
                             String[] tab = aux.split(",");
                             if (count > 0){
                                 try {
                                    jObject.put("name", tab[0]);
                                    jObject.put("load", tab[1]);
                                    jArray.put(jObject);
                                } catch (JSONException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                             }
                             count++;

                            }

                            retVal = jArray.toString();
                     }
                 }

              }
             return retVal;
         }finally{
             httpClient.getConnectionManager().shutdown();
         }

您正在使用相同的对象并在循环中覆盖它。 这个实例化:

 JSONObject jObject = new JSONObject();

一定在您的循环中。

 try {
     JSONObject jObject = new JSONObject();
     jObject.put("name", tab[0]);
     jObject.put("load", tab[1]);
     jArray.put(jObject);
  }