如何使用post方法将JSON数组发送到服务器?

时间:2017-10-09 06:27:13

标签: android json

如何使用post方法将JSON数组发送到服务器?

{
 "user_id":"1",
 "username":"shubham",
 "order":[{"product_id":"2","qty":"5","price":"100","total":"500","product_name":"choclate"},{"product_id":"1","qty":"2","price":"50","total":"500","product_name":"choclate"}]
}

2 个答案:

答案 0 :(得分:0)

您可以使用以下方法创建JSON,并通过您使用的任何库将其发送到服务器

private JSONObject getRequestJSON(){
    JSONObject jsonObject=null;
    try {
        jsonObject= new JSONObject();
        jsonObject.put("user_id", 1);
        jsonObject.put("username", "Shubham");
        //Order Array
        JSONArray orderJson=new JSONArray();
        //Order Object
        JSONObject orderObject=new JSONObject();
        orderObject.put("product_id",2);
        orderObject.put("qty",5);
        orderObject.put("price",100);
        orderObject.put("total",500);
        orderObject.put("product_name","choclate");
        // Add Order object to order array
        orderJson.put(orderObject);
        //Order Object
        JSONObject orderObject1=new JSONObject();
        orderObject1.put("product_id",3);
        orderObject1.put("qty",2);
        orderObject1.put("price",100);
        orderObject1.put("total",200);
        orderObject1.put("product_name","choclate");
        orderJson.put(orderObject1);
        //Add order array to main jsonObject
        jsonObject.put("order",orderJson);

    }catch (JSONException e){
        e.printStackTrace();
    }
    return jsonObject;
}

答案 1 :(得分:0)

在模块级gradle文件中添加依赖项。

compile'com.google.code.gson:gson:2.7'

为您的json模型创建一个类

public class OrderRequest{
   int user_id;
   String username;
   List<Order> order;
   public class Order{
        int product_id;
        int qty;
        float price;
        float total;
        String product_name;
   }
}

在您的活动中创建上述类的对象并设置所有值。

Gson gson = new Gson();
String orderJson = gson.toJson(orderRequestObject);

将orderJson设置为post参数。

相关问题