Pages

Friday 10 February 2012

WEBSERVICES-Read JSON object from webservices url

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import com.ge.energy.pgs.myfleet.tpo.service.UpsFiltersService;
import com.ge.energy.pgs.myfleet.tpo.util.UPSDTO;
import com.ge.energy.pgs.myfleet.tpo.util.PropertyFileReader;
public class ReadJSONFromWebservice {

        try{
        URL url = new URL("http://localhost:8080/WebServices/empData");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");
        if (conn.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
        }
        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
        String jsonString = null;
        String output = null;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            jsonString = output;
            System.out.println(output);
        }
        try {
            JSONObject ups = new JSONObject(jsonString).getJSONObject("empNames");
           
            //String abc = (String)js.get("menuBeanObj");
            JSONArray  nameList     =  ups.getJSONArray("frameTypesList");
            System.out.println("nameList***********"+nameList);
       
        } catch (JSONException e) {
            // TODO Auto-generated catch block
           
            e.printStackTrace();
        }
       
       
        }catch(Exception ex){
           
        }
        return upsDTO;
    }

}

Required : json.jar