[英]java.lang.String cannot be converted to JSONObject
在我的Android應用程序中,我調用一個Web服務,並且返回一個jsonobject。在設備中,我得到一個這樣的響應。
"{ \"Time_Stamp\" : \"10/10/2012 4:26 PM\", \"records\" : [ { \"'Name'\" : \"'LD-00000002'\", \"'Appointment_Date_Time'\" : \"'null'\", \"'Phone'\" : \"'9909955555'\", \"'Home_Country_Address'\" : \"'null'\", \"'Occupation'\" : \"'null'\", \"'SR_Appointment_Status'\" : \"'Open'\", \"'Id'\" : \"'a0OE0000001iLynMAE'\", \"'SR_Appointment_Comment'\" : \"'testing'\", \"'ProductsOfInterest'\" : \"'null'\", \"'ActivityName'\" : \"'Sales'\", \"documentsList\" : [ ] }, { \"'Name'\" : \"'LD-00000002'\", \"'Appointment_Date_Time'\" : \"'null'\", \"'Phone'\" : \"'9909955555'\", \"'Home_Country_Address'\" : \"'null'\", \"'Occupation'\" : \"'null'\", \"'SR_Appointment_Status'\" : \"'Open'\", \"'Id'\" : \"'a0OE0000001iLynMAE'\", \"'SR_Appointment_Comment'\" : \"'testing'\", \"'ProductsOfInterest'\" : \"'null'\", \"'ActivityName'\" : \"'Sales'\", \"documentsList\" : [ { \"numberOfImages\" : 3, \"Name\" : \"new document\", \"Mandatory\" : false, \"FilePath\" : null, \"Category\" : null } ] } ]}"
我試圖將其轉換為這樣的對象
JSONObject jsonObj=new JSONObject(objMngr.getResponse());
轉換時拋出一個異常“ java.lang.String無法轉換為JSONObject” ...下面是確切的異常,它是throwig ..是什么原因,我如何解決這個問題?
{ "Time_Stamp" : "10/10/2012 4:26 PM", "records" : [ { "'Name'" : "'LD-00000002'", "'Appointment_Date_Time'" : "'null'", "'Phone'" : "'9909955555'", "'Home_Country_Address'" : "'null'", "'Occupation'" : "'null'", "'SR_Appointment_Status'" : "'Open'", "'Id'" : "'a0OE0000001iLynMAE'", "'SR_Appointment_Comment'" : "'testing'", "'ProductsOfInterest'" : "'null'", "'ActivityName'" : "'Sales'", "documentsList" : [ ] }, { "'Name'" : "'LD-00000002'", "'Appointment_Date_Time'" : "'null'", "'Phone'" : "'9909955555'", "'Home_Country_Address'" : "'null'", "'Occupation'" : "'null'", "'SR_Appointment_Status'" : "'Open'", "'Id'" : "'a0OE0000001iLynMAE'", "'SR_Appointment_Comment'" : "'testing'", "'ProductsOfInterest'" : "'null'", "'ActivityName'" : "'Sales'", "documentsList" : [ { "numberOfImages" : 3, "Name" : "new document", "Mandatory" : false, "FilePath" : null, "Category" : null } ] } ]} of type java.lang.String cannot be converted to JSONObject
嘗試
JSONObject jsonObj=new JSONObject(objMngr.getResponse().toString().replace("\\", " "));
您的jsonString似乎還可以。 但是,您的響應類型可能不是字符串。 試試吧。 問題在於服務器發送的轉義逗號已經轉義。
首先將您的響應轉換為字符串,然后嘗試創建JSONObject
我認為getResponse()已經是字符串,但是響應不是有效的JSON。如果響應不是字符串,則可以使用toString()方法轉換字符串。
您的字符串上似乎有一些隱藏的字符。 嘗試這個
return new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
好像您在服務器端兩次將對象轉儲到JSON字符串一樣。
對象--dumps()-> json字符串--dumps()-> json中的一個字符串
因此,您應該刪除第二個轉儲。
否則,您可以以這種方式取消轉義字符串。 如何取消Java中的Java字符串文字轉義? 。
我認為第一種方法更好,更輕松。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.