0

i have created a rest wcf web service and hosted in local iis, the json string is converted with JsonConvert.SerializeObject(object) of Newtonsoft package.

the output of the web service is

"[{\"companyId\":2,\"companyName\":\"A\"},
{\"companyId\":8,\"companyName\":\"B\"}]"

this web service is consume by android apps, i tried with JSONArray and JSONObject but it keep on throwing exception

org.json.JSONException: Expected literal value at character 2 of   
[{\"companyId\":2,\"companyName\":\"A\"},{\"companyId\":8,\"companyName\":\"B\"}]
org.json.JSONException: Expected literal value at character 2 of 
"[{\"companyId\":2,\"companyName\":\"A\"},    
{\"companyId\":8,\"companyName\":\"B\"}]"
org.json.JSONException: Value [{"companyId":2,"companyName":"A"},
{"companyId":8,"companyName":"B"}] of type java.lang.String cannot be 
converted to JSONArray

this is the code in android class

public JSONArray RequestWebService(URL urlToRequest) {
urlConnection = (HttpURLConnection) urlToRequest.openConnection();
        urlConnection.setConnectTimeout(CONNECTION_TIMEOUT);
        urlConnection.setReadTimeout(RETRIEVE_TIMEOUT);
        urlConnection.setRequestMethod("GET");
        urlConnection.connect();

int statusCode = urlConnection.getResponseCode();

        if (statusCode == HttpURLConnection.HTTP_OK) {
            InputStream in = new BufferedInputStream(
                    urlConnection.getInputStream());
            String result = getResponseText(in);
            //result = result.substring(1, result.length() - 1);
            //result = result.replace("/\\/g", "");
            JSONArray j = new JSONArray(result);
            return j
        }
    return null;
}

private String getResponseText(InputStream inStream) throws IOException {
    StringBuilder sb = new StringBuilder();
    BufferedReader rd = null;
    try{
        rd = new BufferedReader(new InputStreamReader(inStream));
        String line;
        while ((line = rd.readLine()) != null) {
            sb.append(line);
        }
    }finally {
        if (rd != null) {
            rd.close();
        }
    }

    return sb.toString();
}
Yu Yenkan
  • 745
  • 1
  • 9
  • 32

1 Answers1

0
String response = "Your Response";
try{    
    JsonArray jAry = new JsonArray(response);
        JsonObjct jObj;

        for(int i=0;i<jAry.length;i++){
            jObj = JAry.getJsonObject(i);

  // You can get your string from object jobj and also use it by store it value in arraylist.
        }
  } catch(Exception e){

}
Vishal Patoliya ツ
  • 3,170
  • 4
  • 24
  • 45