我的项目有一个WCF,可以从数据库获取记录并以JSON格式返回,如下所示:
{"GetNotesResult":"[{\"ID\":1,\"Title\":\"Note 1\",\"Content\":\"Hello Vu Chien Thang\",\"CreatedBy\":\"thangvc\"},{\"ID\":2,\"Title\":\"Note 2\",\"Content\":\"Hello Nguyen Thi Ngoc\",\"CreatedBy\":\"thangvc\"}]"}
我也有一个Android应用程序来使用JSON,这是我的代码:
private JSONArray getNotes(String UserName, String Password) { JSONArray jarray = null; JSONObject jobj = null; try{ StringBuilder builder = new StringBuilder(URL); builder.append("UserName=" + loggedInUser.getUserName()); builder.append("&"); builder.append("Password=" + loggedInUser.getPassword()); HttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(builder.toString()); HttpResponse response = client.execute(httpGet); int status = response.getStatusLine().getStatusCode(); if(status==200) { HttpEntity entity = response.getEntity(); String data = EntityUtils.toString(entity,"utf-8"); jobj = new JSONObject(data); jarray = jobj.getJSONArray("GetNotesResult"); } else { Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show(); } } catch(ClientProtocolException e) { Log.d("ClientProtocol",e.getMessage()); } catch(IOException e) { Log.d("IOException", e.getMessage()); } catch(JSONException e) { Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show(); } catch(Exception e) { Log.d("Unhandle Error", e.getMessage()); } return jarray; }
我在处设置了断点,jarray = jobj.getJSONArray("GetNotesResult");并从中得到了以下消息JSONException:
jarray = jobj.getJSONArray("GetNotesResult");
JSONException
Value [{"ID":1,"Title":"Note 1","Content":"Hello Vu Chien Thang","CreatedBy":"thangvc"},{"ID":2,"Title":"Note 2","Content":"Hello Nguyen Thi Ngoc","CreatedBy":"thangvc"}] at GetNotesResult of type java.lang.String cannot be converted to JSONArray
我试图复制JSON字符串并粘贴到在线JSON解析器网站http://jsonviewer.stack.hu/上,它解析得很好。请帮我解决这个问题!
在您的json中,的值GetNotesResult包含在其中,""因此将其视为字符串而不是数组。
GetNotesResult
""
被解析为一个数组。
{"GetNotesResult":[{\"ID\":1,\"Title\":\"Note 1\",\"Content\":\"Hello Vu Chien Thang\",\"CreatedBy\":\"thangvc\"},{\"ID\":2,\"Title\":\"Note 2\",\"Content\":\"Hello Nguyen Thi Ngoc\",\"CreatedBy\":\"thangvc\"}]}
因此,解决方案是两件事之一:
String notes = jobj.getString("GetNotesResult"); jarray = new JSONArray(notes);