在请求正文中发送数组不起作用:使用改进2.1.0

时间:2017-05-31 06:59:14

标签: android web-services retrofit

发送" CustomDishItems"作为数组,它给出结果:服务器遇到处理请求的错误

适用于:" CustomDishItems":""

以下是我要求的数据" POST"在使用PHP Web服务的服务器上

服务网址:

https://csed-ad.epfen.com/test

请求正文:

{
    "AvailableFrom": "",
    "AvailableQty": "1",
    "AvailableTill": "Enter custom Date",
    "AvailableTo": "Jun 15, 2017",
    "Calories": "100",
    "Category": "nonVeg",
    "CreateDate": "May 31, 2017 12:10 PM",
    "CuisineId": "113",
    "CustomDishItems": [{
        "Cost": "100",
        "ItemName": "salted"
    }, {
        "Cost": "120",
        "ItemName": "sweet"
    }],
    "Customizable": "true",
    "Description": "test",
    "DishId": "0",
    "DishName": "test",
    "Ingredeients": "test",
    "MenuTitle": "menu1",
    "PreparingTime": "58",
    "Price": "100",
    "ProfileId": "227",
    "SessionToken": "97801380243422832"
}

Java代码是:

private void addDish(){

    CustomDishField customDishField = new CustomDishField(itemNameEt.getText().toString(), itemCostEt.getText().toString());

    ArrayList<CustomDishField> customDishArrayList = new ArrayList<>();
    customDishArrayList.add(customDishField);

    final int childcount = container.getChildCount();
    for (int i = 0; i < childcount; i++) {
        View v = container.getChildAt(i);

        EditText itemCostEt = (EditText) v
                .findViewById(R.id.itemCostEt);
        EditText itemNameEt = (EditText) v
                .findViewById(R.id.itemNameEt);

        customDishArrayList.add(new CustomDishField(itemNameEt.getText().toString(), itemCostEt.getText().toString()));


    }


    AddDish addDish = new AddDish(availableFrom, availableQuantity, availableTill, availableTo,
            calories, Category
            , createDate, cuisineId, customDishArrayList, Customizable, Description,
            DishId, dishNameString, Ingredeients, MenuTitle, PreparingTime,
            Price, ProfileId, SessionToken);
    Call call = apiInterface.addDish(addDish);

    call.enqueue(new Callback() {
        @Override
        public void onResponse(Call call, retrofit2.Response response) {
            Log.d("TAG", response.code() + "");

            Response response1 = (Response) response.body();


           if (((Response) response.body()).getReturnCode().equals("1")) {

               Toast.makeText(AddDishActivity.this, "" + ((Response)
                               response.body()).getReturnMessage(),
                       Toast.LENGTH_SHORT).show();
               progressBar.setVisibility(View.GONE);
               finish();

               Intent intent = new Intent(AddDishActivity.this, ManageKitchen.class);
               startActivity(intent);

            } else {
                Toast.makeText(AddDishActivity.this, "" + ((Response)
                                response.body()).getReturnCode(),
                        Toast.LENGTH_SHORT).show();
               progressBar.setVisibility(View.GONE);
            }


        }

        @Override
        public void onFailure(Call call, Throwable t) {
            Log.d("TAG", "call cancel");
            call.cancel();
            progressBar.setVisibility(View.GONE);
        }
    });
}

AddDish.Java

公共类AddDish {

@SerializedName("AvailableFrom")
@Expose
private String availableFrom;
@SerializedName("AvailableQty")
@Expose
private String availableQty;
@SerializedName("AvailableTill")
@Expose
private String availableTill;
@SerializedName("AvailableTo")
@Expose
private String availableTo;
@SerializedName("Calories")
@Expose
private String calories;
@SerializedName("Category")
@Expose
private String category;
@SerializedName("CreateDate")
@Expose
private String createDate;
@SerializedName("CuisineId")
@Expose
private String cuisineId;
@SerializedName("CustomDishItems")
@Expose
private ArrayList<CustomDishField> customDishItems;
@SerializedName("Customizable")
@Expose
private String customizable;
@SerializedName("Description")
@Expose
private String description;
@SerializedName("DishId")
@Expose
private String dishId;
@SerializedName("DishName")
@Expose
private String dishName;
@SerializedName("Ingredeients")
@Expose
private String ingredeients;
@SerializedName("MenuTitle")
@Expose
private String menuTitle;
@SerializedName("PreparingTime")
@Expose
private String preparingTime;
@SerializedName("Price")
@Expose
private String price;
@SerializedName("ProfileId")
@Expose
private String profileId;
@SerializedName("SessionToken")
@Expose
private String sessionToken;


public AddDish(String availableFrom, String availableQty,
               String availableTill, String availableTo, String calories,
               String category, String createDate, String cuisineId,
               ArrayList<CustomDishField> customDishItems, String customizable,
               String description, String dishId, String dishName,
               String ingredeients, String menuTitle, String preparingTime,
               String price, String profileId, String sessionToken) {

    this.availableFrom = availableFrom;
    this.availableQty = availableQty;
    this.availableTill = availableTill;
    this.availableTo = availableTo;
    this.calories = calories;
    this.category = category;
    this.createDate = createDate;
    this.cuisineId = cuisineId;
    this.customDishItems = customDishItems;
    this.customizable = customizable;
    this.description = description;
    this.dishId = dishId;
    this.dishName = dishName;
    this.ingredeients = ingredeients;
    this.menuTitle = menuTitle;
    this.preparingTime = preparingTime;
    this.price = price;
    this.profileId = profileId;
    this.sessionToken = sessionToken;
}

public String getAvailableFrom() {
    return availableFrom;
}

public void setAvailableFrom(String availableFrom) {
    this.availableFrom = availableFrom;
}

public String getAvailableQty() {
    return availableQty;
}

public void setAvailableQty(String availableQty) {
    this.availableQty = availableQty;
}

public String getAvailableTill() {
    return availableTill;
}

public void setAvailableTill(String availableTill) {
    this.availableTill = availableTill;
}

public String getAvailableTo() {
    return availableTo;
}

public void setAvailableTo(String availableTo) {
    this.availableTo = availableTo;
}

public String getCalories() {
    return calories;
}

public void setCalories(String calories) {
    this.calories = calories;
}

public String getCategory() {
    return category;
}

public void setCategory(String category) {
    this.category = category;
}

public String getCreateDate() {
    return createDate;
}

public void setCreateDate(String createDate) {
    this.createDate = createDate;
}

public String getCuisineId() {
    return cuisineId;
}

public void setCuisineId(String cuisineId) {
    this.cuisineId = cuisineId;
}

public ArrayList<CustomDishField> getCustomDishItems() {
    return customDishItems;
}

public void setCustomDishItems(ArrayList<CustomDishField> customDishItems) {
    this.customDishItems = customDishItems;
}

public String getCustomizable() {
    return customizable;
}

public void setCustomizable(String customizable) {
    this.customizable = customizable;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public String getDishId() {
    return dishId;
}

public void setDishId(String dishId) {
    this.dishId = dishId;
}

public String getDishName() {
    return dishName;
}

public void setDishName(String dishName) {
    this.dishName = dishName;
}

public String getIngredeients() {
    return ingredeients;
}

public void setIngredeients(String ingredeients) {
    this.ingredeients = ingredeients;
}

public String getMenuTitle() {
    return menuTitle;
}

public void setMenuTitle(String menuTitle) {
    this.menuTitle = menuTitle;
}

public String getPreparingTime() {
    return preparingTime;
}

public void setPreparingTime(String preparingTime) {
    this.preparingTime = preparingTime;
}

public String getPrice() {
    return price;
}

public void setPrice(String price) {
    this.price = price;
}

public String getProfileId() {
    return profileId;
}

public void setProfileId(String profileId) {
    this.profileId = profileId;
}

public String getSessionToken() {
    return sessionToken;
}

public void setSessionToken(String sessionToken) {
    this.sessionToken = sessionToken;
}

}

CustomDishField.Java类是:

公共类CustomDishField {

@SerializedName("ItemName")
@Expose
private String ItemName;
@SerializedName("Cost")
@Expose
private String Cost;

public CustomDishField(String itemName, String cost) {
    ItemName = itemName;
    Cost = cost;
}

public String getItemName() {
    return ItemName;
}

public void setItemName(String itemName) {
    ItemName = itemName;
}

public String getCost() {
    return Cost;
}

public void setCost(String cost) {
    Cost = cost;
}

}

2 个答案:

答案 0 :(得分:0)

我遇到过同样的问题,我必须将JSONArray传递给注册请求。 这是我得到的解决方案。

首先创建一个名为ApiClient的类,如下所示:

    public class ApiClient {

    private static Retrofit retrofit = null;
    private static String BASE_URl = Urls.BASE_URL;


    public static Retrofit getClient() {
        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        httpClient.connectTimeout(20 * 1000, TimeUnit.MILLISECONDS);
        httpClient.readTimeout(20 * 1000, TimeUnit.MILLISECONDS);
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        httpClient.addInterceptor(loggingInterceptor);

        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .client(httpClient.build())
                    .baseUrl(BASE_URl)
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }

        return retrofit;

    }
}
  1. 创建一个接口来调用apiclient类,如下所示:

    public interface ApiInterface {

        @POST(Urls.registerUserUrl)
        Observable<LoginResponseEntity> getRegistrationResponse(@Body JsonObject request); // make sure JsonObject should be from com.google.gson
    }
    
  2. 现在调用解析器:

    ApiInterface apiService =
            ApiClient.getClient().create(ApiInterface.class);
    Observable<LoginResponseEntity> call = apiService.getRegistrationResponse(getRegistrationRequestParameters());
    call.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new DisposableObserver<LoginResponseEntity>() {
                @Override
                public void onNext(LoginResponseEntity loginResponseEntity) {
                    // handle your response here
                }
    
                @Override
                public void onError(Throwable e) {
    
                }
    
                @Override
                public void onComplete() {
                }
            });
    
    
    
    private JsonObject getRegistrationRequestParameters() {
    JSONObject commonParameters = UDF.commonParametersForJson(activity);
    try {
        JSONObject parentInformation = new JSONObject();
        parentInformation.put("firstname", "" + firstName);
        parentInformation.put("lastname", "" + lastName);
        parentInformation.put("contact", "" + phoneNumber);
        parentInformation.put("password", "" + password);
        commonParameters.put("personalinfo", parentInformation);
        JSONObject childObject = null;
        JSONArray childInformation = new JSONArray();
        for (int i = 0; i < alChildRequestEntity.size(); i++) {
            childObject = new JSONObject();
            childObject.put("childname", alChildRequestEntity.get(i).getName());
            childObject.put("pickupstopcode", alChildRequestEntity.get(i).getPickup_stop());
            childObject.put("dropoffstopcode", alChildRequestEntity.get(i).getDrop_stop());
            childInformation.put(childObject);
        }
        commonParameters.put("childinfo", childInformation);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    JsonParser jsonParser = new JsonParser();
    JsonObject gsonObject = (JsonObject) jsonParser.parse(commonParameters.toString());   // make sure JsonObject should be from com.google.gson
    return gsonObject;
    

    }

答案 1 :(得分:0)

使用以下代码将Arraylist转换为字符串并且其工作正常:

Gson gson = new Gson();         String customDishListString = gson.toJson(customDishArrayList);