简体   繁体   中英

How to POST multiple JSON arrays using retrofit (Android, Java)

This is the structure of the post JSON array, I have tried many solutions but no one helped. Thanks in advance.

{[['itemId'=>1,'quantity'=>3],['itemId'=>4,'quantity'=>1]]}

Postman api structure 在此处输入图像描述

You could create an object which has an arraylist of objects like so:

public class MyAwesomeObject {
    public ArrayList<MyObject> awesomeName;
}

class MyObject {
    public String itemId;
    public int quantity;
    public ArrayList<String> someMoreFields;
}

So then you could include this object in your Retrofit POST call:

@POST("awesomeServiceURL")
Single<AnswerDto> myCall(@Body MyAwesomeObject myAwesomeObject);

What I have done for the above structure:

@FormUrlEncoded
@POST("order")
Call<YourResponse> postMethod(@Field("shippingAddress") String shippingAddress,
                              @Field("items[0][id]") List<String> itemList,
                              @Field("items[0][quantity]") List<String> quantityList);

and in your activity or fragment:

List<String> itemList = new ArrayList<>();
List<String> quantityList = new ArrayList<>();
itemList.add("1","2");
quantityList.add("10","20");

and retrofit call:

  Call<YourResponse> checkOut = BaseNetworking.apiServices(AppRepository.mAPIToken(getActivity()))
            .checkOut("this is some address", itemList, quantityList);
    checkOut.enqueue(new Callback<YourResponse>() {
        @Override
        public void onResponse(Call<YourResponse> call, Response<YourResponse> response) {
            if (response.body().getCode() == 200) {
                Toast.makeText(getActivity(), response.body().getMessage(), Toast.LENGTH_SHORT).show();
            } else {
                try {
                    JSONObject jsonObject = new JSONObject(response.errorBody().string());
                    Toast.makeText(getActivity(), jsonObject.getString("message"), Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }

        @Override
        public void onFailure(Call<YourResponse> call, Throwable t) {

        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM