java 如何使用 Retrofit 2 发布 JSON 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41820740/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 06:11:10  来源:igfitidea点击:

How to Post JSON array using Retrofit 2

javaandroidjsonretrofit2

提问by Vinoth Kannan

I need to post an JSON object using Retrofit 2. My JSON object is

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

{ "logTime" : "", "datas" : [ { "dat1": "1", " dat2": "", " dat3": "", " dat4": "", " dat5": ""
}, { "dat1": "1", " dat2": "", " dat3": "", " dat4": "", " dat5": ""
} ]}

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

I have tried using following code:

我尝试使用以下代码:

API Services

应用程序接口服务

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

Activity Class

活动课

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) {

        }
    });

I got "Error: No Retrofit annotation found. (parameter #2)" while using this code. Please help me. Thanks in advance.

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

采纳答案by Rajesh Kanna

Try this code

试试这个代码

Api Services

接口服务

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

API Client

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();

Activity

活动

 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();
        }

    });

回答by Rajesh Koshti

use GSON lib

使用 GSON 库

add this dependency in build.gradle

在 build.gradle 中添加此依赖项

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

API Services

应用程序接口服务

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

Activity Class

活动课

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) {

        }
    });

回答by Eric B.

When using the @FormUrlEncodedannotation, pass parameters using the @Fieldparam instead of @Body. Hence do this:

使用@FormUrlEncoded注解时,使用@Fieldparam 而不是@Body. 因此这样做:

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

I have assumed your server expects a datakey which will have the details. If it is something else, please change it in here @Field("data")

我假设您的服务器需要一个data包含详细信息的密钥。如果是别的东西,请在这里更改@Field("data")

EDIT:

编辑:

Based on the comments:

根据评论:

@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);

回答by Deyan Atanasov

Have you added RetroFit to build.gradle ?

你有没有将 RetroFit 添加到 build.gradle ?

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