如何使用Retrofit 2发布JSON数组

时间:2017-01-24 05:37:43

标签: java android json retrofit2

我需要使用Retrofit 2发布JSON对象。我的JSON对象是

  

{                   “logTime”:“”,                   “数据”:[                         {                           “dat1”:“1”,                           “dat2”:“”,                           “dat3”:“”,                           “dat4”:“”,                           “dat5”:“”                         },                         {                           “dat1”:“1”,                           “dat2”:“”,                           “dat3”:“”,                           “dat4”:“”,                           “dat5”:“”                         }   ]}

我尝试使用以下代码:

API服务

@FormUrlEncoded
@Headers({
        "Content-Type: application/json",
        "x-access-token: eyJhbGciOiJIU"
})
@POST("/api/employee/checkin")
Call<String> CHECKIN(@Body String data);

活动类

JSONStringer jsonStringer = null;
    try {
        jsonStringer=new JSONStringer().object().key("logTime").value("")
                .key("datas")
                .array()
                .object().key("dat1").value("1")
                .key("dat2").value("3")
                .key("dat3").value("5")
                .key("dat4").value("5")
                .endObject()
                .endArray()
                .endObject();
    } catch (JSONException e) {
        e.printStackTrace();
    }

    ApiService service = retroClient.getApiService();

    Call<String> login = service.CHECKIN(String.valueOf(jsonStringer));

    login.enqueue(new Callback<String>() {
        @Override
        public void onResponse(Call<String> call, Response<String> response) {
            dialog.dismiss();
            try {
                String val = response.body();


            } catch (Exception e) {
                e.getMessage();
            }
        }

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

        }
    });

使用此代码时出现“错误:找不到改造注释。(参数#2)”。请帮我。提前谢谢。

4 个答案:

答案 0 :(得分:2)

使用GSON lib

在build.gradle中添加此依赖项

compile 'com.google.code.gson:gson:2.8.0'

API服务

@Headers({
        "Content-Type: application/json",
        "x-access-token: eyJhbGciOiJIU"
})
@POST("/api/employee/checkin")
Call<String> CHECKIN(@Body String data);

活动类

try {

            JsonArray datas = new JsonArray();

            JsonObject object = new JsonObject();
            object.addProperty("dat1","1");
            object.addProperty("dat2", "");
            object.addProperty("dat3", "");
            object.addProperty("dat4", "");
            object.addProperty("dat5", "");

            datas.add(object);

            JsonObject req = new JsonObject();
            req.addProperty("logTime", "");
            req.addProperty("datas", new Gson().toJson(datas));


        } catch (Exception e) {
            e.printStackTrace();
        }



    ApiService service = retroClient.getApiService();

    Call<String> login = service.CHECKIN(String.valueOf(req));

    login.enqueue(new Callback<String>() {
        @Override
        public void onResponse(Call<String> call, Response<String> response) {
            dialog.dismiss();
            try {
                String val = response.body();


            } catch (Exception e) {
                e.getMessage();
            }
        }

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

        }
    });

答案 1 :(得分:2)

试试此代码

Api服务

 @POST("/api/employee/checkin")
Call<Sample> CHECKIN(@Body JSONStringer data);

API客户端

OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
    httpClient.addInterceptor(new Interceptor() {
        @Override
        public Response intercept(Interceptor.Chain chain) throws IOException {
            Request original = chain.request();

            // Request customization: add request headers
            Request.Builder requestBuilder = original.newBuilder()
                    .addHeader("Content-Type", "application/json")
                    .addHeader("x-access-token", "eyJhbGci");

            Request request = requestBuilder.build();
            return chain.proceed(request);
        }
    });

    OkHttpClient client = httpClient.build();



    return new Retrofit.Builder()
            .baseUrl(ROOT_URL)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

活动

 ApiService service = retroClient.getApiService();

    Call<Sample> call = service.CHECKIN(jsonStringer);

    call.enqueue(new Callback<Sample>() {
        @Override
        public void onResponse(Call<Sample> call, Response<Sample> response) {
            dialog.dismiss();
            if (response.isSuccessful()) {
                Sample result = response.body();


            } else {
                // response received but request not successful (like 400,401,403 etc)
                //Handle errors
            }

        }

        @Override
        public void onFailure(Call<Sample> call, Throwable t) {
            dialog.dismiss();
            Toast.makeText(MainActivity.this, "Network Problem", Toast.LENGTH_LONG).show();
        }

    });

答案 2 :(得分:0)

使用@FormUrlEncoded注释时,使用@Field参数而不是@Body传递参数。因此这样做:

@FormUrlEncoded
@Headers({
        "Content-Type: application/json",
        "x-access-token: eyJhbGciOiJIU"
})
@POST("/api/employee/checkin")
Call<String> CHECKIN(@Field("data") String data);

我假设您的服务器需要一个data密钥,其中包含详细信息。如果是其他内容,请在此处@Field("data")

进行更改

修改

根据评论:

@FormUrlEncoded
@Headers({
        "Content-Type: application/json",
        "x-access-token: eyJhbGciOiJIU"
})
@POST("/api/employee/checkin")
Call<String> CHECKIN(@Field("logTime") String logTime, @Field("datas") String datas);

答案 3 :(得分:-1)

您是否已将RetroFit添加到build.gradle?

compile 'com.squareup.retrofit2:retrofit:2.1.0'