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

标签 android json

我在数据库中有一些数据我想用json格式发送数据

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

我想一次将所有记录发送到网络 API。现在我正在一个一个地发送我如何发布这个 json。如何动态地将 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); 

最佳答案

试试这个来创建 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 作为字符串传递给它

关于Android Json 对象和 json 数组发送到 httppost,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24261478/

相关文章:

android - 解决方案 : Android Studio not rendering API 22 activities

android - 如何修复 Android 中使用钛合金的 TableView 中触摸事件和图像消失的问题?

java - Android Studio 无法连接到 Azure sql server 中的数据库

java - 导入新 Gradle 项目失败 : failed to find Build Tools revision *. 0.0

javascript - 寻址 JSON 数组中的对象

javascript - Ajax 如果 JSON 值为 null 设置为空白或不适用

json - 为什么 GraphQL 没有被设计为有效的 json 文档?

java - AlertDialog 自动关闭

java - Java中OutputStream中的String中的引号问题

php - Symfony Controller 中的 json_decode ?