是否可以通过POST发送JSONArray而不是JSONObject?

时间:2015-01-05 21:32:45

标签: java android json http post

关于该主题的SO的大多数答案都围绕着将所有数据发送到一个JSONObject中,其中包含JSONArrays。

如果可能的话,我想做相反的事情。

这里有一些代码:

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

为什么这是错误的做法?

1 个答案:

答案 0 :(得分:1)

是的,这是可能的。

示例:

如果我们将arraylist中的数据上传到服务器上,哟可以用这种方式发送

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

}
相关问题