![](/img/trans.png)
[英]JSONException: Value of type java.lang.String cannot be converted to JSONObject
[英]Android JSONException: Value <script of type java.lang.String cannot be converted to JSONObject
我看到有關此問題的相關問題已發布,但沒有一個解決方案對我有用。 在我的場景中,嘗試從后端發送的JSON響應中檢索值時遇到此錯誤。
這是來自后端的原始JSON響應:
HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Length: 516
Content-Type: application/json; charset=utf-8
Expires: 0
Server: Microsoft-IIS/8.0
X-Powered-By: ASP.NET
Set-Cookie: ARRAffinity=0b;Path=/;Domain=MY-SERVICE-NAME-HERE.azure-mobile.net
Date: Tue, 05 Jan 2016 07:55:00 GMT
{"user":{"id":"349994","firstName":"683hniqnonefw","lastName":"bebweberbw","profilePicture":"683hniqnonefw"},"status":"success","accessToken":"279740","extraData":{"currentAndroidVersion":"4.6.2"}}
我在Android Studio中得到的異常:
org.json.JSONException: Value <script of type java.lang.String cannot be converted to JSONObject
我如何從Android響應中讀取值:
URL url = new URL("http://MY-MOBILE-SERVICE.azure-mobile.net/api/loginuser?email=" + email + "&password=" + pass);
HttpURLConnection urlRequest = (HttpURLConnection) url.openConnection();
urlRequest.setRequestMethod("GET");
urlRequest.addRequestProperty("Content-Type", "application/json");
urlRequest.addRequestProperty("ACCEPT", "application/json");
urlRequest.addRequestProperty("X-ZUMO-APPLICATION", mobileServiceAppId);
JSONObject[] response = null;
InputStream in = new BufferedInputStream(urlRequest.getInputStream());
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(in));
StringBuilder responseString = new StringBuilder();
String line;
while ((line = bufferReader.readLine()) != null) {
responseString.append(line);
}
JSONObject jsonobj1 = new JSONObject(responseString.toString());
//Doesn't reach this point. Crashes before this
Log.d("Check", responseString.toString());
String status = jsonobj1.getString("status");
JSONObject jsonobj = jsonobj1.getJSONObject("user");
根據我在其他Stack答案中所讀內容,當JSON Response String中存在不需要的字符時,會發生這種情況。 即使我知道可能的原因,我也不知道如何解決該問題。 有人可以指出問題所在嗎?
附加:后端使用C#編碼並托管在Microsoft Azure上
編輯:
哈哈哈哈這就是我記錄響應時得到的! 難怪它崩潰了。 但是當我通過Fiddler或任何其他客戶端請求響應時,響應就可以了。 我的Java代碼似乎有誤,是的,這就是我在Android上獲得的實際響應。 提琴手的反應似乎還可以
<script language="javascript">document.location="http://1.1.1.1/process.htm";</script>
使用optString而不是getString。
如評論中所述,問題是您的響應重定向到另一個URL,您的HttpUrlConnection
必須處理重定向。 看到此如何做。
嘗試這個 :
try {
// create http connection
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
// connect
HttpResponse response = client.execute(httpget);
// get response
HttpEntity entity = response.getEntity();
if(entity == null) {
msg = "No response from server";
return null;
}
// get response content and convert it to json string
InputStream is = entity.getContent();
return streamToString(is);
}
catch(IOException e){
msg = "No Network Connection";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.