无法将Json字符串转换为JSONObject或JSONArray

时间:2016-01-28 08:24:04

标签: java c# android json wcf

我创建了一个休息的wcf Web服务并托管在本地iis中,json字符串使用Newtonsoft包的JsonConvert.SerializeObject(object)进行转换。

Web服务的输出是

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

此Android服务由Android应用程序使用, 我尝试使用JSONArray和JSONObject,但它继续抛出异常

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

这是android类中的代码

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

1 个答案:

答案 0 :(得分: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){

}