How to send JSON data as Body using Retrofit android

前端 未结 3 1712
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-06 02:38

I am trying to post below JSON array on server.

{
    \"order\": [{
            \"orderid\": \"39\",
            \"dishid\": \"54\",
            \"quantity\"         


        
相关标签:
3条回答
  • 2021-01-06 03:29

    Create OrderRequest Class

    public class OrderRequest {
    
    @SerializedName("order")
    public List<Order> orders;
    }
    

    create Order Class

        public class Order {
    
        @SerializedName("orderid")
        public String Id;
    }
    

    EndPoint

    public interface ApiEndpoint{
      @POST("order")
      Call<String> createOrder(@Body OrderRequest order, @HeaderMap HashMap<String,String> headerMap);
    }
    

    Use this type of implementation in the mainActivity which call to service

    HashMap hashMap= new HashMap();
        hashMap.put("Content-Type","application/json;charset=UTF-8");
    
    OrderRequest orderRequest = new OrderRequest();
    List<Orders> orderList = new ArrayList();
    
    Orders order = new Order();
    order.Id = "20";
    orderList.add(order);
    //you can add many objects
    
    orderRequest.orders = orderList;
    
    Call<String> dataResponse= apiEndPoint.createOrder(orderRequest,hashMap)
    dataResponse.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                try{
    
                }catch (Exception e){
    
                }
            }   
    

    In the createOrder method we donot need to convert object into Json. Because when we build retrofit we add converter factory as a GsonConverterFactory. It will automatic convert that object to the JSON

     retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
    
    0 讨论(0)
  • 2021-01-06 03:31

    using Retrofit version 2

    compile 'com.squareup.retrofit2:retrofit:2.0.0'
    compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
    
    1. create POJO class that corresponds to JSON structure that you will send to the server:

       public class RequestBody {
            private List<InnerClass> order;
      
            public RequestBody(List<InnerClass> order) {
               this.order = order;
            }
      
            public class InnerClass{
                 private int orderid, dishid, quantity, userid;
      
                 public InnerClass(int orderid, int dishid, int quantity, int userid) {
                   this.orderid = orderid;
                   this.dishid = dishid;
                   this.quantity = quantity;
                   this.userid = userid;
               }
               public int getOrderId() { return orderid; }
               public int getDishId() { return dishid; }
               public int getQuantity() { return quantity; }
               public int getUserId() { return userid; }
            }
       }
      
      1. Create a servicegenerator class to initialize your Retrofic object instance:

         public class ServiceGenerator {
        
          private static OkHttpClient okHttpClient = new OkHttpClient();
        
           public static <S> S createService(Class<S> serviceClass) {
           Retrofit.Builder builder = new Retrofit.Builder()
                                   .baseUrl(AppConfig.BASE_URL)
                                     .addConverterFactory(GsonConverterFactory.create());
          Retrofit retrofit = builder.client(okHttpClient).build();
        
          return retrofit.create(serviceClass);
        }
        
    2. create the api service interface which should contain "updateorder" method:

      public interface ApiService {
          @POST("updateorder.php")
          Call<your POJO class that corresponds to your server response data> updateorder(@Body RequestBody object);
      }
      

    4.inside your activity or fragment where you would like to make the request fill your Json data and initialize ApiService:

    ArrayList<RequestBody.InnerClass> list = new List<>();
    list.add(new RequestBody.InnerClass(39, 54, 4, 2));
    list.add(new RequestBody.InnerClass(39, 54, 4, 2));
    RequestBody requestBody = new RequestBody(list);
    
         ApiService apiService =    ServiceGenerator.createService(ApiService.class);
       Call<your POJO class that corresponds to your server response data> call = apiService.updateorder(requestBody);
    //use enqueue for asynchronous requests 
    call.enqueue(new Callback<your POJO class that corresponds to your server response data>() {
    
       public void onResponse(Response<> response, Retrofit retrofit) {
             M.hideLoadingDialog();
            Log.e("ssss",s.toString());
            Log.e("ssss", response.getReason());
       }
    
       public void onFailure(Throwable t) {
               M.hideLoadingDialog();
               Log.e("error",t.toString());
            }
    }
    
    0 讨论(0)
  • 2021-01-06 03:33

    try to modify your code to Retrofit 2

    compile 'com.squareup.retrofit2:retrofit:2.0.0'
    compile 'com.squareup.retrofit2:converter-gson:2.0.0'
    

    Your service :

    @POST("updateorder.php")
    Call<String> updateorder(@Body JsonObject object);
    

    Call retrofit

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(RetrofitService.baseUrl)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    

    Pass your Json using GSON :

    JsonObject postParam = new JsonObject
    postParam.addProperty("order",yourArray) ;
    

    Finally :

    Call<String> call = retrofitService.updateorder(postParam);
    
    
        call.enqueue(new Callback<String>() {
             @Override
             public void onResponse(Call<String>callback,Response<String>response) {
                String res = response.body();
             }
                @Override
                public void onFailure(Call<String> call, Throwable t) {
    
                }
        });
    

    I hope to be helpful for you .

    0 讨论(0)
提交回复
热议问题