gson 如何使用Retrofit android将JSON数据作为Body发送

pbpqsu0x  于 2022-11-06  发布在  Android
关注(0)|答案(4)|浏览(287)

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

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

}

我在下面使用这个:

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

    });

}

我收到以下错误:

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 $

更新Api代码:

@POST("updateorder.php")
    void updateorder(@Body JSONObject object,Callback<String>());

有谁能告诉我我的错误吗?
先谢谢你

o8x7eapl

o8x7eapl1#

创建OrderRequest类

public class OrderRequest {

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

创建订单类

public class Order {

    @SerializedName("orderid")
    public String Id;
}

终点

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

在调用服务的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){

            }
        }

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

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

tvokkenx2#

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

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

您的服务:

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

呼叫改装

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

使用GSON传递JSON:

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

最后道:

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

            }
    });

我希望能对你有所帮助。

t3psigkw

t3psigkw3#

If you want to post a JSON request using Retrofit then there are two methods to follow.

1. Option one - Seraialized Object
Create a serializable object(In simple terms convert your JSON object into a class) and post it using Retrofit.
If you don't know how to do it use this URL to

将JSon对象转换为类jsonschema2pojo

Example : Lets say in your case JSon object class name is Order.

然后在类中定义与JSon结构匹配的变量。([]定义的内部块是一个对象数组)。并且必须定义getter和setter(为了保存空间,我在这里没有包括它们)

public class Order implements Serializable{
private List<Order> order = null; //Include getters and setters
}

2. Option Two - Raw json (I prefer this one)
Create a JsonObject object and pass it (Remember not a JSONObject. Though both appears to be the same there is a distinct difference between them. Use exact same characters)

JsonObject bodyParameters = new JsonObject();
JsonArray details= new JsonArray();
JsonObject orderData= new JsonObject();
orderData.addProperty("orderid", "39");//You can parameterize these values by passing them
orderData.addProperty("dishid", "54");
orderData.addProperty("quantity", "4");
orderData.addProperty("userid", "2");
details.add(orderData)
bodyParameters.add("order", details);

Create Retrofit instance
retrofit = new Retrofit.Builder()
                    .baseUrl(baseURL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(okHttpClient)
                    .build();

Retrofit Service(You have to create a service class and define instance)
@POST("<Your end point>")
Call<ResponseObject> updateOrder(@Body JsonObject bodyParameters);

Request Call
Call<ResponseObject> call = postsService.updateOrder(bodyParameters);
//postsService is the instance name of your Retrofit Service class
wlp8pajw

wlp8pajw4#

使用改型版本2

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

1.创建POJO类,它对应于您将发送到服务器的JSON结构:

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.创建一个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);
}

1.创建应包含“updateorder”方法的api服务接口:

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

4.在您的Activity或片段中,您希望在其中发出请求,填充您的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());
        }
}

相关问题