Android - 解析单项响应JSONObject

Rmi*_*372 2 android json

我对这个问题很感兴趣(大约需要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");
                } 
Run Code Online (Sandbox Code Playgroud)

nha*_*man 7

我不是很熟悉JSON解析,但基于这个例子,我认为你应该//parse json data改成这个:

//parse json data
try {
    JSONObject userObject = new JSONObject(result);
    userID = userObject.getString("id");
} catch(Exception ex){
    //don't forget this
}
Run Code Online (Sandbox Code Playgroud)

那就是如果调用new JSONObject(result)是正确的.之前提到的示例显示如下:

JSONObject userObject = (JSONObject) JSONSerializer.toJSON( result );
Run Code Online (Sandbox Code Playgroud)