0

我正在将 Eclipse 用于必须从 URL 读取 JSON 文件的应用程序。

我正在使用的代码是这个:

http://collegewires.com/android/2012/06/json-parsing-in-android/

好的,我用来读取 JSON 文件的 CLASS 叫做 Parser.java:

package com.cw.json;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

public class Parser {

    static InputStream is = null;
    static JSONObject jsonObject = null;
    static String json = "";
    // class constructor
    public Parser() {

    }

    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();           

        } catch (UnsupportedEncodingException exception) {
            exception.printStackTrace();
        } catch (ClientProtocolException exception) {
            exception.printStackTrace();
        } catch (IOException exception) {
            exception.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sBuilder = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sBuilder.append(line + "\n");
            }
            is.close();
            json = sBuilder.toString();
        } catch (Exception exception) {
            exception.printStackTrace();
        }

        // Parsing the string to a JSON object
        try {
            jsonObject = new JSONObject(json);
        } catch (JSONException exception) {
            exception.printStackTrace();
        }

        // JSON String
        return jsonObject;

    }
}

我正在使用此代码来读取直接是 ARRAY 的 JSON 文件,但该代码给了我一个错误。

我的问题是:是否可以读取数组而不是始终读取对象?也许使用另一个类?

4

1 回答 1

0

尝试将您的 Parser.java 修改为此,因此您得到一个数组而不是对象。并且请给你买一本 JAVA 书给初学者,这样你就可以学习如何说 JAVA

 public JSONArray getJSONFromUrl(String url) {
    ....
    static JSONArray jsonArray = null;
    ....
     // Parsing the string to a JSON Array
     try {
            jsonArray = new JSONArray(json);
     } catch (JSONException exception) {
            exception.printStackTrace();
     }
     return jsonArray;
  }
于 2013-10-15T17:23:03.533 回答