How to Post JSON array using Retrofit 2
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) {
}
});
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();
}
});