Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Post JSON array using Retrofit 2

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

{ "logTime" : "", "datas" : [ { "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.

like image 255
Vinoth Kannan Avatar asked Jan 24 '17 05:01

Vinoth Kannan


People also ask

How to convert JSON array to model class in retrofit?

The answer is that we just pass a List of model class and Retrofit convert JSON Array object to the corresponding Model class. Here is our JSON Array response get from the Server after calling a request API. Here is our description function of API Interface. Here is our Retrofit call function, that is called the API via Retrofit Client.

How to add retrofit API in Android app?

Navigate to the app > java > your app’s package name > Right-click on it > New > Java class select it as Interface and name the file as RetrofitAPI and add below code to it. Comments are added inside the code to understand the code in more detail. // GET as annotation.

How do okhttp and retrofit work with arrays?

Retrofit and OkHttp will then build an appropriate multipart request with all files. Java arrays or lists allow you to freely add files as required. You know the theory, so it's time to look at an example.

What is Retrofit 2 library?

In this one, we will use a library (Retrofit) for doing the same. Retrofit 2 is a HTTP client written in java. It is a type safe library that makes HTTP API calls. You can then convert it into different formats and parse them to java interfaces or classes as neeeded.


2 Answers

use GSON lib

add this dependency in 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) {

        }
    });
like image 106
Rajesh Koshti Avatar answered Oct 10 '22 04:10

Rajesh Koshti


Try this code

Api Services

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

API Client

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

    });
like image 22
Rajesh Kanna Avatar answered Oct 10 '22 06:10

Rajesh Kanna