Sign up ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Since I've looked far and wide for a good example of this to no avail, I have created my own using the JSONArray and JSONObject classes. It took me a while to realize that the push method for JSONObject overwrites everything previously pushed.

public class PieChartData{

private static Logger logger = LoggerFactory.getLogger(PieChartData.class);
private static String envURL = System.getProperty("publicWebsite.env.url");

public PieChartData(){

}

public static JSONArray getJSON(String dataLocation)throws IOException, URISyntaxException, TransformerException, JSONException {

    return getCSV(dataLocation);
}


public static JSONArray getCSV(String url) throws IOException, JSONException{
    url = url.replace("ex.com", envURL + "ex.com");
    String retVal = "";
    HttpClient httpClient = new DefaultHttpClient();
    JSONObject jObject = null;
    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){
                            jObject = new JSONObject();
                            jObject.put("name", tab[0]);
                            jObject.put("load", tab[1]);
                            jArray.put(jObject);
                        }
                        count++;
                     }
                     retVal = jArray.toString();
                 }
             }

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

}

share|improve this question
1  
The amazing Jackson library supports CSV data format as well. – Simon Forsberg Sep 19 at 21:27

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.