将List <model>更新后2.0改为服务器

时间:2017-12-13 19:22:55

标签: android json retrofit2

我正在使用retrofit 2.0从服务器发送我的ArrayList,但我总是收到一个错误。它是:预期BEGIN_ARRAY但是STRING在第1行第1列路径$。 服务器等待这种类型json:

    Param "array":
[
    {"number": "required*", "name": "required*", "lastname": "", "email":""},
    {"number": "required*", "name": "required*", "lastname": "", "email":""},
    {"number": "required*", "name": "required*", "lastname": "", "email":""},
    ...
]

标头中的

和用户身份验证令牌。 要发送我的数据,我正在使用此代码:

private void sendUserPhoneBook(String access_token) {
    UserPhoneBookData userPhoneBookData = new UserPhoneBookData(LoginActivity.this);
    ArrayList<PhoneContactModel> list = userPhoneBookData.getPhoneBook();

    Server service = retrofit.create(Server.class);
    Call<ArrayList<PhoneContactModel>> call = service.sendPhoneBookApi(access_token,list);
    call.enqueue(new Callback<ArrayList<PhoneContactModel>>() {
        @Override
        public void onResponse(Call<ArrayList<PhoneContactModel>> call, Response<ArrayList<PhoneContactModel>> response) {
            if (response.isSuccessful()) {
                // запрос выполнился успешно, сервер вернул Status 200
                Log.d(LOG_TAG, "-sendUserPhoneBook" + String.valueOf(response.code()));

            } else {
                // сервер вернул ошибку
            }
        }

        @Override
        public void onFailure(Call<ArrayList<PhoneContactModel>> call, Throwable t) {
            // ошибка во время выполнения запроса
            Log.d(LOG_TAG, "-sendUserPhoneBookErr = " + t.getMessage());

        }
    });

}

PhoneContactModel.class看起来像:

public class PhoneContactModel {
public String name;
public String email;
public String number;
public String lastname;


public PhoneContactModel(String name, String email, String phoneNumber,String lastname) {
    this.name = name;
    this.email = email;
    this.number = phoneNumber;
}..more

我的Server.class有@POST看起来像:

@POST("/api/import")
Call<ArrayList<PhoneContactModel>> sendPhoneBookApi(@Header("TOKEN") String token, @Body ArrayList<PhoneContactModel> list);

请帮助我做! P.S .:接受我的英语

1 个答案:

答案 0 :(得分:0)

您需要封装此数组列表。所以创建类

public class ImportRequest
{
    private ArrayList<PhoneContactModel> list;
    public ImportRequest(ArrayList<PhoneContactModel> list){
        this.list = list;
    }
}

并将其用作正文:

@POST("/api/import")
Call<ArrayList<PhoneContactModel>> sendPhoneBookApi(@Header("TOKEN") String token, @Body ImportRequest request);