Merge/concatenate jsonObjects

public static JSONObject concat(@NonNull JSONObject[] objs) {
        ArrayList<JSONObject> jsonObjectArrayList = new ArrayList<>();

        for (JSONObject o : objs) {
            if (o.length() > 0) {
                jsonObjectArrayList.add(o);
            }
        }

        JSONObject merged = new JSONObject();
        JSONObject[] jsonObjects = jsonObjectArrayList.toArray(
                new JSONObject[jsonObjectArrayList.size()]);
        for (JSONObject obj : jsonObjects) {
            Iterator it = obj.keys();
            while (it.hasNext()) {
                String key = (String) it.next();
                Object value = null;

                try {
                    value = obj.get(key);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                try {
                    merged.put(key, value);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        return merged;
    }

 

Working example POST in android

Here is another short (IMHO) example how to post in android app.

[java]
private void postSms(String text) {
URL url;
HttpURLConnection urlConnection = null;

try {
url = new URL(“http://yourserver.com/sendsms”);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod(“POST”);
urlConnection.setDoOutput(true);

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(“sms”, text));//POST param as “sms”

OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, “UTF-8”));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();

String status = new String(Streams.getBytes(urlConnection.getInputStream()));
Log.d(TAG, new Exception().getStackTrace()[0].getMethodName() + “:insert status=” + status);

} catch (MalformedURLException | ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
[/java]

This is a method for concatenating parameters for POST

Continue reading “Working example POST in android”