2017-10-09 8 views
-3

postメソッドを使用して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"}] 
} 
+0

まず、これはJson配列ではありません。これは配列要素を持つJsonです。ジャックスRsを見ましたか? – user641887

+0

無効なJSON配列の閉じ括弧 ']' '配列'の配列 – akhilesh0707

+0

これは、私がサーバー上で送信しなければならないデータの形式です –

答えて

0

あなたは、あなたのモジュールレベルGradleのファイルに依存関係を追加します

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

を使用している方法の下に使用してJSONを作成し、どのようなライブラリを介してサーバに送信することができます。

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

postパラメータとしてorderJsonを設定します。

関連する問題