Barry_D_Dale
Barry_D_Dale

Reputation: 131

Concatinating JSON elements using java-json

I have a program that reads in a CSV file and returns a JSON String.

However using JsonArray and JsonObject only yield the last row of results from the file. How do I concat numerous rows of data into a JSON object?

Output

[{"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"}]

Code

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();
         }

Upvotes: 1

Views: 38

Answers (1)

HulkSmash
HulkSmash

Reputation: 396

You are using same object and over-writing it in your loop. This instantiation:

 JSONObject jObject = new JSONObject();

must be in your loop.

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

Upvotes: 1

Related Questions