Android Json对象和json数组发送到httppost

时间:2014-06-17 10:29:44

标签: android json

我在数据库中有一些数据要在json中发送数据

       {"name":"Ram","age":20},
       {"name":"michael","age":25},
       {"name":"Suma","age":28}

我想一次将所有记录发送到网络API。现在我逐个发送如何发布这个json.How如何动态地将json对象分配给json数组。?

     JSONObject obj = new JSONObject();
   try {

    obj.put("Name","Ram");
    obj.put("age",20);

    HttpContext httpContext = new BasicHttpContext();
    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, 2000);
    HttpConnectionParams.setSoTimeout(httpParameters, 2000);
    HttpClient httpClient = new DefaultHttpClient(httpParameters);
    HttpPost httpPost = new HttpPost("myurl");
    try {
        StringEntity se = new StringEntity(obj.toString());
        httpPost.setEntity(se);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");
        HttpResponse response = httpClient.execute(httpPost, httpContext); //execute your        HttpEntity entity = response.getEntity();
        String jsonString = EntityUtils.toString(entity); //if response in JSON format
        System.out.println("Respone: "+jsonString); 

1 个答案:

答案 0 :(得分:1)

尝试使用此方法创建JSON ARRAY ..

JSONArray myArray = new JSONArray();

JSONObject j = new JSONObject();
    j.put("key",value);
    j.put("key",value);
    myarray.put(j);
JSONObject j = new JSONObject();
    j.put("key",value);
    j.put("key",value);
    myarray.put(j);
JSONObject j = new JSONObject();
    j.put("key",value);
    j.put("key",value);
    myarray.put(j);

JSONObject finalObject = new JSONObject();
finalObject.put("Name", myarray);

然后将 finalObject 传递给字符串