将Java对象转换为JSON数组以进行Retrofit调用

时间:2017-12-21 16:47:17

标签: java json retrofit2

我需要使用Retrofit调用发送一个字符串数组。为此,我决定创建一个像这样的对象:

public class SendEmailsList {

    ArrayList<String> emails;

    public SendEmailsList(ArrayList<String> emails) {
        this.emails = emails;
    }
}

我的JSON字符串必须是这样的:

{
  "emails": ["email@server.com","email1@server.com","email2@server.com"]
}

这是我界面中定义的POST方法:

@POST("/v2/companies/{companyId}/invite")
  Call<ArrayList<String>> inviteMembers(@Path("companyId") String companyId, @Body SendEmailsList emails);

这是进行Retrofit调用的方法:

public void SendNetworkRequest() {

    OkHttpClient.Builder okhttpBuilder = new OkHttpClient.Builder();

    okhttpBuilder.addInterceptor(new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {

            Request request = chain.request();

            Request.Builder newRequest = request.newBuilder().header("Authorization", "Bearer " + token);

            return chain.proceed(newRequest.build());
        }
    });

    Retrofit.Builder builder = new Retrofit.Builder()
            .baseUrl(BuildConfig.ENDPOINT)
            .client(okhttpBuilder.build())
            .addConverterFactory(GsonConverterFactory.create());

    Retrofit retrofit = builder.build();
    CompanyService invite = retrofit.create(CompanyService.class);

        Call<ArrayList<String>> call = invite.inviteMembers("5602eb7ce49c9cd70409f206", new SendEmailsList(invitedEmails));
        call.enqueue(new Callback<ArrayList<String>>() {
            @Override
            public void onResponse(Call<ArrayList<String>> call, Response<ArrayList<String>> response) {

                System.out.println("Internal Users: " + response.code());

            }

            @Override
            public void onFailure(Call<ArrayList<String>> call, Throwable t) {
                // Log error here since request failed
                Log.e("Internal Users Activity", t.toString());
            }
        });
    }

但是我收到了这个错误:

12-21 14:36:49.953 27953-27953/com.construct.test E/Internal Users Activity: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

我如何弄清楚发生了什么?

0 个答案:

没有答案