【发布时间】:2017-01-19 23:37:53
【问题描述】:
我在这个问题上处于领先地位(大约需要 6 个小时才能完成这项工作),我知道我在这里遗漏了一些完全简单的东西。
我正在尝试使用一条数据解析 JSON 响应,但我的解析代码无法识别它。
这是整个 JSON 响应...
{"id":"4480"}
“4480”是一个潜在的字母数字数据响应,因此它也可能类似于“A427”。
这是我用来尝试解析单个响应的代码。问题是 userID 为 null - 它没有在 JSON 响应中获取 4480。有人可以指出我在哪里搞砸了吗?非常感谢我能得到的任何帮助!
InputStream is = null;
//http post
try{
String postQuery = "my api post goes here";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(postQuery);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try {
JSONObject userObject = new JSONObject(result);
JSONObject jsonid = userObject.getJSONObject("id");
userID = jsonid.getString("id");
}
【问题讨论】:
-
搞砸了什么?你期待没有发生的事情吗?你有例外吗?如果是这样,请发布堆栈跟踪。
-
userID 为空,所以我的解析代码实际上并没有抓取 4480
-
那么如果您尝试记录结果字符串,它是否正确检索数据?
-
是的 - 我得到的字符串就好了。它在 //parse json 数据代码中的某个地方,我做得不对。