【问题标题】:android : converting ArrayList to JSON and post to a urlandroid : 将 ArrayList 转换为 JSON 并发布到 url
【发布时间】:2018-02-04 15:18:18
【问题描述】:

**你好亲爱的朋友们,在我的项目中,我有一个每秒从信标数据填充的数组列表,是否可以将此数组 L 转换为 JSONArray 并同时将其发布到 URL ??? **

'private ArrayList<Beacon> arrayL = new ArrayList<>();

@Override
public void onBeaconServiceConnect() {

    iBeaconManager.setRangeNotifier(new RangeNotifier() {
        @Override
        public void didRangeBeaconsInRegion(final Collection<Beacon> iBeacons, Region region) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    arrayL.clear();
                    arrayL.addAll((ArrayList<Beacon>) iBeacons);

                }
            });
        }
    });'

enter image description here

【问题讨论】:

标签: android


【解决方案1】:

你可以试试这样的:

1) 构建 JSON 对象

ArrayList<Beacon> arrayL = new ArrayList<>();
JSONArray mJSONArray = new JSONArray(Arrays.asList(arrayL));

2) 发布到服务器

public void postData() {
    ArrayList<String> arrayL = new ArrayList<>();
    JSONArray mJSONArray = new JSONArray(Arrays.asList(arrayL));
    URL url = null;
    try {
        url = new URL("http://www.android.com/");
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    HttpURLConnection connection = null;
    try {
        connection = (HttpURLConnection) url.openConnection();
    } catch (IOException e) {
        e.printStackTrace();
    }
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setRequestProperty("Accept", "application/json");
    connection.setRequestProperty("Content-Type", "application/json");
    try {
        connection.setRequestMethod("POST");
    } catch (ProtocolException e) {
        e.printStackTrace();
    }

    for(int i = 0; i < mJSONArray.length(); i++)
    {
        try {
            JSONObject objects = mJSONArray.getJSONObject(i);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //Iterate through the elements of the array i.
        //Get thier value.
        //Get the value for the first element and the value for the last element.
    }
    JSONObject json = new JSONObject();

    byte[] outputBytes = new byte[0];
    try {
        outputBytes = json.toString().getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    OutputStream os = null;
    try {
        os = connection.getOutputStream();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        os.write(outputBytes);
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        os.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-06
    • 1970-01-01
    • 2020-04-30
    • 2014-01-15
    • 2020-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多