繁体   English   中英

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

[英]cannot convert Json string to JSONObject or JSONArray

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

Web服务的输出是

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

此网络服务被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();
}
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){

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM