[英]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.