2017-08-26 56 views
-2

**你好亲爱的朋友,在我的项目中,我有一个ArrayList每秒填充信标数据,是否有可能将此arrayL转换为JSONArray并将其发布到URL与此同时 ??? **android:将ArrayList转换为JSON并发布到网址

'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

+0

[将ArrayList 转换为JSONArray]的可能重复(https://stackoverflow.com/questions/4841952/convert-arraylistmycustomclass-to-jsonarray) – mismanc

回答

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(); 
    } 
} 

希望它成真PS。

+0

tnx,但是当我用你的方式,我的应用程序得到了力量关闭... – amirofff