【发布时间】:2013-04-03 10:45:17
【问题描述】:
我的项目有一个 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\"}]"}
我还有一个使用 JSON 的 Android 应用程序,这是我的代码:
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 得到这条消息:
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 字符串复制并粘贴到http://jsonviewer.stack.hu/ 的在线 JSON 解析器网站,它解析得很好。请帮我解决这个问题!
【问题讨论】:
-
JsonArray 不正确
-
当然我已经在清单文件中添加了 INTERNET 权限。我什至使用另一个功能登录到我的 android 应用程序来连接服务器
-
亲爱的 Sameer,我使用 LINQtoSQL DataContext 和 JavaScriptSerializer 来序列化结果,这是我从浏览器获取的原始 JSON,你能告诉我更多关于 JSON 格式的问题吗?