【问题标题】:Converting JSONObject to JSONArray将 JSONObject 转换为 JSONArray
【发布时间】:2016-06-05 01:56:22
【问题描述】:

我目前正在学习一些使用 JAVA 的 Android 编程。我的老师分享了这段代码,它将使用一个 API,获取它的 JSON 文件,并将其转换为 JSONArray 文件。然后他将遍历该 JSONArray 并将它们放入 ArrayList 中,然后再将它们显示到活动中。

问题是我正在使用的 API 返回一个 JSONObject 文件,而我不知道如何正确地将其转换为 JSONArray。

import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;

public class JSONParser {

String charset = "UTF-8";
HttpURLConnection conn;
DataOutputStream wr;
StringBuilder result;
URL urlObj;
JSONArray jObj = null;
StringBuilder sbParams;
String paramsString;

public JSONArray makeHttpRequest(String url, String method) {

    sbParams = new StringBuilder();

   if(method.equals("GET")){
        // request method is GET

        if (sbParams.length() != 0) {
            url += "?" + sbParams.toString();
        }

        try {
            urlObj = new URL(url);

            conn = (HttpURLConnection) urlObj.openConnection();

            conn.setDoOutput(false);

            conn.setRequestMethod("GET");


            conn.setRequestProperty("AccountKey", "pVU56+0hI26DNLeTzlU/Dw==");
            conn.setRequestProperty("UniqueUserId", "33c07f2f-b4c0-4151-acd3-e0829b303d2c");
            conn.setRequestProperty("accept", "application/json");

            conn.setConnectTimeout(15000);

            conn.connect();

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

    }

    try {
        //Receive the response from the server
        InputStream in = new BufferedInputStream(conn.getInputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        result = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            result.append(line);
        }

        Log.d("JSON Parser", "result: " + result.toString());

    } catch (IOException e) {
        // e.printStackTrace();
    }

    conn.disconnect();

    // try parse the string to a JSON object
    try {

        jObj = new JSONArray(result.toString());
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON Object
    return jObj;
}

}

API URL 及其自定义标头:

URL: http://datamall2.mytransport.sg/ltaodataservice/TaxiAvailability

标题-

AccountKey: pVU56+0hI26DNLeTzlU/Dw==
UniqueUserId: 33c07f2f-b4c0-4151-acd3-e0829b303d2c
accept: application/json

EDIT2:我使用它来获取带有自定义标题的原始数据。 http://requestmaker.com/

编辑:这是我得到的 JSON。

{
  "odata.metadata": "http://datamall2.mytransport.sg/ltaodataservice/$metadata#TaxiAvailability",
  "value": [
    {
      "Longitude": 103.84009,
      "Latitude": 1.35989
    },
    {
      "Longitude": 103.84679,
      "Latitude": 1.35544
    },
    {
      "Longitude": 103.76928,
      "Latitude": 1.4419
    }
    ....
    ]
    }

【问题讨论】:

  • 请发布您的 JSON。
  • 用它编辑。看看吧。
  • JSONObject json_obj = new JSONObject(json_string); JSONArray 数组 = json_obj.getJSONArray("值")

标签: java android arrays json jsonobject


【解决方案1】:

用这个代替jObj = new JSONArray(result.toString());

JSONObject obj = new JSONObject(result.toString());
JSONArray arr = obj.getJSONArray("value");

现在您可以按照自己的方式使用JSONArray arr

【讨论】:

  • 感谢您的快速帮助!所以据我所知,数组在值“打开”之后开始是吗?
  • 是的,正确。它将包含所有经纬度组 (JSONObject)。
  • 那我应该为arr创建一个局部变量吗?因为我不能使用 arr 在第二个 try-catch 上解析它,因为它是在第一个 try-catch 中声明的。
  • 只需将此代码放在第二个 try-catch 中。我没有注意到你有两个 try-catch 块。也编辑了我的答案。
  • 如果 Object 中没有值怎么办,我有这样的 JSON 代码 '{ "42": "42 Coin", "365": "365Coin", "404": "404Coin" ,“611”:“SixEleven”,“808”:“808”,“888”:“Octocoin”,“1337”:“1337”,“2015”:“2015 硬币”,“CLUB”:“ClubCoin”, "007": "007 coin", "ZRX": "0x", "BIT16": "16BitCoin" } 我怎样才能把它转换成 JSONObject 到 JSONArray
【解决方案2】:
JSONObject Jobj = new JSONObject(result.toString());
JSONArray Jarray = obj.getJSONArray("value");

你需要的是Jarray

然后迭代Jarray获取对象中的对象和值Longitude,Latitude。

【讨论】:

    猜你喜欢
    • 2019-08-17
    • 2011-11-03
    • 2018-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多