Java 解析给出ClassCastException的Json数据
我目前正在使用以下JSON解析器,但不断得到由以下原因引起的错误:java.lang.ClassCastException:java.lang.String无法转换为org.JSON.JSONObject。我怎样才能解决这个问题,它以前已经工作过很多次了Java 解析给出ClassCastException的Json数据,java,json,api,parsing,Java,Json,Api,Parsing,我目前正在使用以下JSON解析器,但不断得到由以下原因引起的错误:java.lang.ClassCastException:java.lang.String无法转换为org.JSON.JSONObject。我怎样才能解决这个问题,它以前已经工作过很多次了 ublic List<String> handleResponse(HttpResponse response) throws ClientProtocolException, IOException
ublic List<String> handleResponse(HttpResponse response)
throws ClientProtocolException, IOException {
List<String> result = new ArrayList<String>();
String JSONResponse = new BasicResponseHandler()
.handleResponse(response);
try {
// Get top-level JSON Object - a Map
JSONObject responseObject = (JSONObject) new JSONTokener(
JSONResponse).nextValue(); //Problem Line
JSONObject item1 = responseObject.getJSONObject("searchResult");
// Extract value of "Item" key -- a List
JSONArray items = item1
.getJSONArray("Item");
您的nextValue()方法必须返回一个字符串,然后尝试将其强制转换为JSONObject。首先,我将把声明分成几个较小的声明,以帮助隔离问题。您正在实例化一个新对象,对其调用一个方法,并在同一行上键入casting。这使得代码更难调试
JSONTokener tokener = new JSONTokener(JSONResponse);
Object obj = tokener.nextValue();
if(obj.getClass().equals(JSONObject.class))
{
JSONObject responseObject = (JSONObject)obj;
}
else
{
System.out.println("Not a JSONObject");
}
为什么您需要一个
JSONTokener
?这要容易得多:
JSONObject responseObject = new JSONObject(JSONResponse);
JSONArray main = responseObject.getJSONArray("findItemsAdvancedResponse");
JSONObject result = main.getJSONObject(0).getJSONArray("searchResult").getJSONObject(0);
JSONArray items = result.getJSONArray("item");
查看它时,
nextValue()
将返回一个字符串
,这似乎是完全正确的。也许你的回答不是你所期望的格式。使用它如何帮助你?得到一个不匹配的例外我在我的应用程序中使用这个方法,它工作得很好。你能发布你的新源代码和准确的错误信息吗?我已经更新了我的答案。代码使用JSON进行了测试,运行良好。
JSONObject responseObject = new JSONObject(JSONResponse);
JSONArray main = responseObject.getJSONArray("findItemsAdvancedResponse");
JSONObject result = main.getJSONObject(0).getJSONArray("searchResult").getJSONObject(0);
JSONArray items = result.getJSONArray("item");