java - 异步类无法打印出 JSON 提要的内容

标签 java android json

我的 Async 类不会显示 JSON Feed 的内容,我收到错误:

01-17 15:44:35.438: W/System.err(1732): org.json.JSONException: Value null of type org.json.JSONObject$1 cannot be converted to JSONArray.

我假设我的 readJSONFeed 方法可能返回空字符串,但我不知道为什么。代码如下,如果有人能看到问题,我将不胜感激。

public class JSONActivity extends Activity {

public String readJSONFeed(String URL) {
    StringBuilder stringBuilder = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(URL);
    try{
        HttpResponse response = client.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if(statusCode == 200){
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null); {
                stringBuilder.append(line);
            }

        }else{
            Log.e("JSON", "Failed to download file");
        }
    }catch(ClientProtocolException e) {
        e.printStackTrace();
    }catch(IOException e) {
        e.printStackTrace();
    }

    return stringBuilder.toString();
}

private class ReadJSONFeedTask extends AsyncTask<String, Void, String> {

    protected String doInBackground(String... urls){
        return readJSONFeed(urls[0]);
    }

    protected void onPostExecute(String result){
        try{
            JSONArray jsonArray = new JSONArray(result);
            Log.i("JSON", "Number of surverys in feed: " +
                    jsonArray.length());


            //---print out the content of the JSON feed---
            for(int i = 0; i < jsonArray.length(); i++){
                JSONObject jsonObject = jsonArray.getJSONObject(i);


                Toast.makeText(getBaseContext(), jsonObject.getString("appeId") +
                        " - " + jsonObject.getString("inputTime"), 
                        Toast.LENGTH_SHORT).show();



            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_json);

new ReadJSONFeedTask().execute("http://extjs.org.cn/extjs/examples/grid/survey.html");

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.json, menu);
    return true;
}

}

日志猫

01-17 16:18:17.388: D/(1868): HostConnection::get() New Host Connection established 0xb7bd6ed0, tid 1868
01-17 16:18:17.458: W/EGL_emulation(1868): eglSurfaceAttrib not implemented
01-17 16:18:17.458: D/OpenGLRenderer(1868): Enabling debug mode 0
01-17 16:18:18.178: W/System.err(1868): org.json.JSONException: Value null of type org.json.JSONObject$1 cannot be converted to JSONArray
01-17 16:18:18.228: D/dalvikvm(1868): GC_FOR_ALLOC freed 240K, 10% free 3042K/3356K, paused 36ms, total 40ms
01-17 16:18:18.258: W/System.err(1868):     at org.json.JSON.typeMismatch(JSON.java:111)
01-17 16:18:18.258: W/System.err(1868):     at org.json.JSONArray.<init>(JSONArray.java:96)
01-17 16:18:18.258: W/System.err(1868):     at org.json.JSONArray.<init>(JSONArray.java:108)
01-17 16:18:18.258: W/System.err(1868):     at com.example.json.JSONActivity$ReadJSONFeedTask.onPostExecute(JSONActivity.java:66)
01-17 16:18:18.258: W/System.err(1868):     at com.example.json.JSONActivity$ReadJSONFeedTask.onPostExecute(JSONActivity.java:1)
01-17 16:18:18.258: W/System.err(1868):     at android.os.AsyncTask.finish(AsyncTask.java:632)
01-17 16:18:18.258: W/System.err(1868):     at android.os.AsyncTask.access$600(AsyncTask.java:177)
01-17 16:18:18.258: W/System.err(1868):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
01-17 16:18:18.258: W/System.err(1868):     at android.os.Handler.dispatchMessage(Handler.java:102)
01-17 16:18:18.268: W/System.err(1868):     at android.os.Looper.loop(Looper.java:137)
01-17 16:18:18.268: W/System.err(1868):     at android.app.ActivityThread.main(ActivityThread.java:4998)
01-17 16:18:18.268: W/System.err(1868):     at java.lang.reflect.Method.invokeNative(Native Method)
01-17 16:18:18.268: W/System.err(1868):     at java.lang.reflect.Method.invoke(Method.java:515)
01-17 16:18:18.268: W/System.err(1868):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
01-17 16:18:18.268: W/System.err(1868):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
01-17 16:18:18.268: W/System.err(1868):     at dalvik.system.NativeStart.main(Native Method)

最佳答案

您不小心在 while 语句之后放置了一个 ;,因此您的 StringBuilder 对象中实际上没有任何内容,因此当您进入时您的字符串为 null onPostExecute()

while ((line = reader.readLine()) != null); {  // <-- oops
    stringBuilder.append(line);
}

看去掉分号时是否正常。

关于java - 异步类无法打印出 JSON 提要的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21195844/

相关文章:

java - 通过连接 Java 中给定字符串集的最后一个字母来创建一个新字符串

java - 哪种递归方法更好?为什么对于整数的反转数字?

android - 带有复选框的android ListView 中未触发复选框单击事件

php - 在 Laravel 中验证 JSON 数组

json - 如何添加utf8解码器解决flutter http请求乱码问题?

Java:LDAP 搜索返回 1 行

java - eclipse java中三种不同方法增加JVM堆内存失败

java - Android - 如何避免 Activity 之间的重复代码

android - 数据绑定(bind)通用变量

json - 在 Golang 中解码任意 JSON