Reputation: 49
Most of the answers on SO on the subject revolve around sending all your data inside one JSONObject, with the JSONArrays inside.
I would like to do the opposite, if possible.
Here's some code:
JSONObject winnerJSONObject = new JSONObject();
JSONObject loserJSONObject = new JSONObject();
try{
winnerJSONObject.put(Columns.ID.toString(), winner.getId());
winnerJSONObject.put(Columns.NAME.toString(), winner.getName());
winnerJSONObject.put(Columns.SCORE.toString(),winner.getScore());
winnerJSONObject.put(Columns.WINS.toString(), winner.getWins());
winnerJSONObject.put(Columns.LOSSES.toString(), winner.getLosses());
winnerJSONObject.put(Columns.MAX_SCORE.toString(),winner.getMaxScore());
winnerJSONObject.put(Columns.MIN_SCORE.toString(),winner.getMinScore());
loserJSONObject.put(Columns.ID.toString(), loser.getId());
loserJSONObject.put(Columns.NAME.toString(), loser.getName());
loserJSONObject.put(Columns.SCORE.toString(),loser.getScore());
loserJSONObject.put(Columns.WINS.toString(),loser.getWins());
loserJSONObject.put(Columns.LOSSES.toString(),loser.getLosses());
loserJSONObject.put(Columns.MAX_SCORE.toString(),loser.getMaxScore());
loserJSONObject.put(Columns.MIN_SCORE.toString(),loser.getMinScore());
} catch (JSONException e) {
e.printStackTrace();
}
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = null;
try {
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept", "application/json");
httpPost.setEntity(new StringEntity(jsonArray.toString(), HTTP.UTF_8));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
httpResponse = httpClient.execute(httpPost);
} catch (IOException e) {
e.printStackTrace();
}
JSONArray jsonArray = new JSONArray();
jsonArray.put(winnerJSONObject);
jsonArray.put(loserJSONObject);
Why is this a wrong approach?
Upvotes: 0
Views: 1563
Reputation: 1477
Yes it is possible.
Example:
Like if we have our data in arraylist to upload on server, Yo can send it in this way
JsonArray _array = new JsonArray()
for(i = 0; i< _arraylist.size(); i++){
JsonObject obj = new JsonObject();
obj.put(_array.list.get(i).getValue);
_array.put(obj);
}
}
Upvotes: 1