如何使用Retrofit Android将JSON数据作为主体发送

May*_*rel 5 android json gson retrofit

我正在尝试在服务器上的JSON数组下面发布。

{
    "order": [{
            "orderid": "39",
            "dishid": "54",
            "quantity": "4",
            "userid":"2"
        },{
            "orderid": "39",
            "dishid": "54",
            "quantity": "4",
            "userid":"2"
        }]

}
Run Code Online (Sandbox Code Playgroud)

我在下面使用这个:

private void updateOreder() {

    M.showLoadingDialog(GetDishies.this);
    UpdateAPI mCommentsAPI = APIService.createService(UpdateAPI.class);

    mCommentsAPI.updateorder(jsonObject, new Callback<String>() {
        @Override
        public void success(String s, Response response) {
            M.hideLoadingDialog();
            Log.e("ssss",s.toString());
            Log.e("ssss", response.getReason());
        }

        @Override
        public void failure(RetrofitError error) {
            M.hideLoadingDialog();
            Log.e("error",error.toString());
        }

    });

}
Run Code Online (Sandbox Code Playgroud)

我得到以下错误:

 retrofit.RetrofitError: com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 2 column 6 path $
Run Code Online (Sandbox Code Playgroud)

updateApi代码:

@POST("updateorder.php")
    void updateorder(@Body JSONObject object,Callback<String>());
Run Code Online (Sandbox Code Playgroud)

有人可以告诉我我的错误吗?

提前致谢

Abb*_*ine 5

尝试将您的代码修改为Retrofit 2

compile 'com.squareup.retrofit2:retrofit:2.0.0'
compile 'com.squareup.retrofit2:converter-gson:2.0.0'
Run Code Online (Sandbox Code Playgroud)

您的服务:

@POST("updateorder.php")
Call<String> updateorder(@Body JsonObject object);
Run Code Online (Sandbox Code Playgroud)

通话改造

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(RetrofitService.baseUrl)
        .addConverterFactory(GsonConverterFactory.create())
        .build();
Run Code Online (Sandbox Code Playgroud)

使用GSON传递您的Json:

JsonObject postParam = new JsonObject
postParam.addProperty("order",yourArray) ;
Run Code Online (Sandbox Code Playgroud)

最后:

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

            }
    });
Run Code Online (Sandbox Code Playgroud)

希望对您有所帮助。


Ish*_*ndo 5

创建订单请求类

public class OrderRequest {

@SerializedName("order")
public List<Order> orders;
}
Run Code Online (Sandbox Code Playgroud)

创建订单类

    public class Order {

    @SerializedName("orderid")
    public String Id;
}
Run Code Online (Sandbox Code Playgroud)

端点

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

在调用服务的 mainActivity 中使用这种类型的实现

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

            }
        }   
Run Code Online (Sandbox Code Playgroud)

在 createOrder 方法中,我们不需要将对象转换为 Json。因为当我们构建改造时,我们将转换器工厂添加为 GsonConverterFactory。它会自动将该对象转换为 JSON

 retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
Run Code Online (Sandbox Code Playgroud)


tsi*_*iro 0

使用改造版本 2

compile 'com.squareup.retrofit2:retrofit:2.0.0'
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
Run Code Online (Sandbox Code Playgroud)
  1. 创建与您将发送到服务器的 JSON 结构相对应的 POJO 类:

     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; }
          }
     }
    
    Run Code Online (Sandbox Code Playgroud)
    1. 创建一个 servicegenerator 类来初始化您的 Retrofic 对象实例:

       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);
      }
      
      Run Code Online (Sandbox Code Playgroud)
  2. 创建 api 服务接口,其中应包含“updateorder”方法:

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

4.在您的活动或片段中,您希望请求填充您的 Json 数据并初始化 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());
        }
}
Run Code Online (Sandbox Code Playgroud)