Retrofit is a popular REST client for Android and Java developed by Square. Using Retrofit one can easily retrieve and upload data via REST based web services. In most of the cases, data are sent through data model class. Sometimes data elements to be sent are not structured or might vary a lot, in those cases raw JSON data could be sent. In this tutorial, we are going to look at how to send raw JSON data using Retrofit.
We are going to use retrofit version 2.1 so we have to add the following dependencies in the app/build.gradle file
dependencies { compile 'com.squareup.retrofit2:retrofit:2.1.0' compile 'com.squareup.retrofit2:converter-gson:2.1.0' }
Now we need to add web service endpoints inside of an interface (Let’s name it IRetrofit) containing special retrofit annotations to include details about the parameters and request methods.
public interface IRetrofit { @Headers({ "Accept: application/json", "Content-Type: application/json" }) @POST("saveRawJSONData") Call<jsonobject> postRawJSON(@Body JsonObject locationPost); }
The above interface will help to call the webservice http://yourwebserviceapi/saveRawJSONData to save the raw JSON data that will be sent as parameter.
Now we are going to create another java class (Let’s name it ServiceGenerator) that will generate Retrofit instances whenever we need to use it.
public class ServiceGenerator { private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); public static <S> S createService(Class<S> serviceClass, String baseUrl) { Retrofit builder = new Retrofit.Builder() .baseUrl(baseUrl) .addConverterFactory(GsonConverterFactory.create()) .client(httpClient.build()) .build(); return builder.create(serviceClass); } }
In the above we added google-gson as our JSON data converter.
Now we shall add code in our MainActivity to send the JSON data. Lets say we want to send the following JSON data
{ "user": "Asif", "cities": ["Dhaka", "Örebro"] }
We can create the JSON object in the following way.
JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("user","Asif"); JsonArray citiesArray = new JsonArray(); citiesArray.add("Dhaka"); citiesArray.add("Örebro"); jsonObject.add("cities", citiesArray);
The rest of the code is simple use of Retrofit library.
// Using the Retrofit IRetrofit jsonPostService = ServiceGenerator.createService(IRetrofit.class, "http://yourwebserviceapi/"); Call<jsonobject> call = jsonPostService.postRawJSON(jsonObject); call.enqueue(new Callback<JsonObject>() { @Override public void onResponse(Call<JsonObject> call, Response<jsonobject> response) { try{ Log.e("response-success", response.body().toString()); }catch (Exception e){ e.printStackTrace(); } } @Override public void onFailure(Call<JsonObject> call, Throwable t) { Log.e("response-failure", call.toString()); } });
The most important point was to use JsonObject of google-gson library instead of JSONObject typically used in creating JSON object, without using JsonObject it would not work as we have used gson as our converter for Retrofit.
The full source code can be downloaded from here
The last statement “The most important point was to use JsonObject of google-gson library instead of JSONObject typically used in creating JSON object, without using JsonObject it” This saved lot of time for me.
Thank you for the great post!!
Hello, I’m developing an app on android to update the user in real time and for this I need to make a post of his location, I’ve been trying for several days through the android. I tested the API via PostMan and it works, but when I used your project it went wrong. Could help? I use ASP.net Core as Web API.
I have to pass the Id, latitude, longitude as parameters in Post
Thank you very much
Hi Roberto,
Could you please mention what error are you getting?
Hi Asif
Thank you very very very much for this excellent post on how to send a DYNAMIC JSON object through Retrofit – that was EXACTLY what I’ve needed for my s/w project
Amir Ingher
Senior s/w engineer
Fortress-GB Ltd
Israel