【问题标题】:retrieve JSON array and put it into an Array in java?检索 JSON 数组并将其放入 java 中的数组?
【发布时间】:2012-06-04 04:28:57
【问题描述】:

我正在检索 JSON 数据数组并尝试显示和访问它。但是当我尝试显示它时,它只显示 JSON 数据数组中的最后一行。当我尝试执行类似 json1.get( 2)(这里的json1是包含JSONObject的JSONArray)我得到数组超出范围的错误。 请告诉我我做错了什么以及如何检索 JSON 下面是这个问题的相关代码。

谢谢。

我从 Freebies.java 类调用 UserFunctions.java 类的 getAllFreebies 函数

UserFunctions uf = new UserFunctions();
JSONObject json = uf.getAllFreebies();

下面是我在 UserFunctions.java 类中的 getAllFreebies() 函数的代码:

public JSONObject getAllFreebies(){
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", getAllFreebies_tag));
    JSONObject json  = jsonParser.getJSONFromUrl(getAllFreebiesURL,params);
    JSONArray json1 = new JSONArray();
    json1.put(json);
    try {
        System.out.println(json1.get(2));
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return json;
}

下面是 index.php 类的代码,我调用 DB_Functions.php 类的 getFreebies() 函数

else if($tag = 'getAllFreebies'){
                $username = "";
                $catagory = "";
                $subcatagory = "";
                $title = "";
                $condition = "";
                $description = "";
                $address = "";
                $city = "";
                $state = "";
                $country = "";
                $zipcode = "";
                $posted_on= "";
                    $getAllFreebies = $db->getFreebies($username,$catagory,$subcatagory,$title,$condition,$description,$address,$city,$state,$country,$zipcode,$posted_on);
            $data = array();
            while($row = mysql_fetch_assoc($getAllFreebies)) {
            $response["success"] = 1;
            $data[] = array(
            $response["getAllFreebies"]["username"] = $row["username"],
            $response["getAllFreebies"]["catagory"] = $row["catagory"],
            $response["getAllFreebies"]["subcatagory"] = $row["subcatagory"],
            $response["getAllFreebies"]["title"] = $row["title"],
            $response["getAllFreebies"]["item_condition"] = $row["item_condition"],
            $response["getAllFreebies"]["description"] = $row["description"],
            $response["getAllFreebies"]["address"] = $row["address"],
            $response["getAllFreebies"]["city"] =  $row["city"],
            $response["getAllFreebies"]["state"] = $row["state"],
            $response["getAllFreebies"]["country"] = $row["country"],
            $response["getAllFreebies"]["zipcode"] = $row["zipcode"],
            $response["getAllFreebies"]["posted_on"] = $row["posted_on"]);}
            echo json_encode($response);
                    }// end of getAllFreebies tag

下面是DB_Functions.php的getFreebies()函数代码

public function getFreebies(){
$result = mysql_query("SELECT * FROM freebie") or die(mysql_error());
return($result);
}

更新:我在 JSONParser 类中添加了以下内容以解析 JSONArray public JSONArray getJSONArrayFromUrl(String url, List params) {

    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(params));
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

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

    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();
        json = sb.toString();

        Log.e("JSON", json);
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
        jarray.put(jObj);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jarray;

}

我更改了 getAllFreebie() 以检索 JSONArray

public JSONArray getAllFreebies() {
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", getAllFreebies_tag));
    JSONArray json = jsonParser.getJSONArrayFromUrl(getAllFreebiesURL,
            params);
    return json;
}

我仍然只得到单行而不是所有行。谁能告诉我我做错了什么。谢谢:(

【问题讨论】:

    标签: java php android mysql json


    【解决方案1】:

    将您的代码更新为:

    // Initialize the array with your JSON string.
    JSONArray json1 = new JSONArray(json);
    
    // This line adds your String as the first element to
    // the JSON array and is incorrect. You can safely remove it.
    //json1.put(json);
    

    编辑:试试您发布的代码的更新版本:

    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(params));
        HttpResponse httpResponse = httpClient.execute(httpPost);
    
        try {
            // Get our response as a String.
            String jsonString = EntityUtils.toString(httpResponse.getEntity());
            Log.d(TAG, "JSON: "+jsonString);
    
            // Parse the JSON String into a JSONArray object.
            return new JSONArray(jsonString);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
    

    【讨论】:

    • 感谢您的响应。我尝试这样做,但 Eclipse 给了我一个错误“构造函数 JSONArray(JSONObject) 未定义”您也可以看看我的 index.php 代码并检查是否一切都正确?我得到 1 行,所以我可能不会得到其他行
    • 对不起,我读错了你的例子。问题出在jsonParser.getJSONFromUrl 方法中。该方法代码是什么样的?那是你写的东西还是你正在使用的库?如果您的 json 变量是包含 JSON 数组的字符串,我发布的代码示例将可以正常工作。
    • 感谢您的回复。该函数只需转到 URL 并检索 JSON。但我不确定我返回的是包含多行数据还是仅包含 1 行数据的 JSON 数组:S
    • 其实你是对的 jsonParser 是错误的。它只解析 Objects。让我尝试为 JSONArray 编写解析器,看看它是否有效。
    • 我已经用您刚刚发布的代码的调整版本更新了我的答案。请尝试一下,看看它是否适合您。
    【解决方案2】:

    检查以下代码:

    JSONObject json  = jsonParser.getJSONFromUrl(getAllFreebiesURL,params);
    JSONArray json1 = new JSONArray();
    json1.put(json);
    try {
        System.out.println(json1.get(2));
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    

    您创建一个新的empty JSONArray,向其中添加一个元素,然后尝试访问它的第二个元素。

    getJSONFromUrl 应该解析对象还是数组?我相信您需要它来返回 JSONArray

    【讨论】:

    • 所以我检索 JSON 数组的函数需要类似 public JSONObject[] getAllFreebies(){} ?!
    • @Viking:我实际上会做JSONArray getAllFreebies(),你不期待一系列 JSON 免费赠品吗?
    • 我还需要在我的 JSONParser 类中编写一个自定义的 getJSONArrayFromURL 方法。getJSONFromUrl 只是获取 JSONObject 而不是 JSONArray。
    猜你喜欢
    • 1970-01-01
    • 2021-06-09
    • 2021-05-11
    • 1970-01-01
    • 1970-01-01
    • 2015-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多