Retrofit 2: Get JSON from Response Body

Retrofit 2: Get JSON from Response body

Use this link to convert your JSON into POJO with select options as selected in image below

Sample Image

You will get a POJO class for your response like this

public class Result {

@SerializedName("id")
@Expose
private Integer id;
@SerializedName("Username")
@Expose
private String username;
@SerializedName("Level")
@Expose
private String level;

/**
*
* @return
* The id
*/
public Integer getId() {
return id;
}

/**
*
* @param id
* The id
*/
public void setId(Integer id) {
this.id = id;
}

/**
*
* @return
* The username
*/
public String getUsername() {
return username;
}

/**
*
* @param username
* The Username
*/
public void setUsername(String username) {
this.username = username;
}

/**
*
* @return
* The level
*/
public String getLevel() {
return level;
}

/**
*
* @param level
* The Level
*/
public void setLevel(String level) {
this.level = level;
}

}

and use interface like this:

@FormUrlEncoded
@POST("/api/level")
Call<Result> checkLevel(@Field("id") int id);

and call like this:

Call<Result> call = api.checkLevel(1);
call.enqueue(new Callback<Result>() {
@Override
public void onResponse(Call<Result> call, Response<Result> response) {
if(response.isSuccessful()){
response.body(); // have your all data
int id =response.body().getId();
String userName = response.body().getUsername();
String level = response.body().getLevel();
}else Toast.makeText(context,response.errorBody().string(),Toast.LENGTH_SHORT).show(); // this will tell you why your api doesnt work most of time

}

@Override
public void onFailure(Call<Result> call, Throwable t) {
Toast.makeText(context,t.toString(),Toast.LENGTH_SHORT).show(); // ALL NETWORK ERROR HERE

}
});

and use dependencies in Gradle

compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.+'

NOTE: The error occurs because you changed your JSON into POJO (by use of addConverterFactory(GsonConverterFactory.create()) in retrofit). If you want response in JSON then remove the addConverterFactory(GsonConverterFactory.create()) from Retrofit. If not then use the above solution

How to get JSON object using Retrofit?

Your interface should look like this :

public interface RetrofitInterface {
@GET("ALE2")
Call<ResponseBody> getData();
}

To get raw json object return type should be Call<ResponseBody>
Once that is done in response you can handle it like below :

retrofit.create(RetrofitInterface.class).getData().enqueue(new Callback<ResponseBody> () {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
String responseBody = response.body().string();
JSONObject json = new JSONObject(responseBody);
}

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

}
});

This is how you can set string in JSON object.

how to get json response using retrofit

Try this :

Api client :

public class ApiClient {


public static final String BASE_URL = "http://zeenatkhanniazai.com/services/";
private static Retrofit retrofit = null;


public static Retrofit getClient() {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}

Api interface :

public interface ApiInterface {

@POST("login.php")
@FormUrlEncoded
Call<users> getTopRatedMovies(@Field("uemail") String uemail, @Field("upassword") String upassword);

}

User class :

public class users
{
@SerializedName("message")
private String message;
@SerializedName("status")
private String status;

public String getStatus() {
return status;
}

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}

public void setStatus(String status) {
this.status = status;
}
}

In main activity :

call.enqueue(new Callback<users>() {
@Override
public void onResponse(Call<users> call, Response<users> response) {
progressDoalog.dismiss();
int statusCode = response.code();
String movies = response.body().getMessage();

Log.e("sdasd",movies);
//Log.w("response",new Gson().toJson(response));
Log.w("response",new GsonBuilder().setPrettyPrinting().create().toJson(response));
// recyclerView.setAdapter(new MoviesAdapter(movies, R.layout.list_item_movie, getApplicationContext()));
}

@Override
public void onFailure(Call<users> call, Throwable t) {
progressDoalog.dismiss();
// Log error here since request failed
Log.e(TAG, t.toString());
}
});

Output :

Login unsuccessful :( This account doesn't exist or the email is not verified yet! try asking admin for activation and then logging in ;)

Response :

"body": {
"message": "Login unsuccessful :( This account doesn\u0027t exist or the email is not verified yet! try asking admin for activation and then logging in ;)",
"status": "0"
},

Android retrofit 2 | get list data from JSON response

@ZookKep - response.body() will return list of objects. You can directly use that. Don't need to any other logic.

I mean don't make .toString() call on response.body().

You can check with log like follows

val listOfModels = response.body()

if (listOfModels != null) {
for ((index, model) in listOfModels.withIndex()) {
Log.d("----", "----")
Log.d("INDEX $index", "ActualTotalLoadByMonthValue ${model.actualTotalLoadByMonthValue}")
Log.d("INDEX $index", "AreaName ${model.areaName}")
Log.d("INDEX $index", "AreaTypeCode ${model.areaTypeCode}")
Log.d("INDEX $index", "Dataset ${model.dataset}")
Log.d("INDEX $index", "MapCode ${model.mapCode}")
Log.d("INDEX $index", "Month ${model.month}")
Log.d("INDEX $index", "ResolutionCode ${model.resolutionCode}")
Log.d("INDEX $index", "Source ${model.source}")
Log.d("INDEX $index", "Year ${model.year}")
Log.d("----", "----")
}
}

Still you have doubt on this please let me know in comments section. I am happy to help :)

Retrofit 2 - parse JSON based on response Type

Since your response type dont change(always give json object) , add all keys within a json object

    public class UserDetail {

@SerializedName("message")
@Expose
private String message;
@SerializedName("customer_id")
@Expose
private Integer customerId;
@SerializedName("customer_name")
@Expose
private String customerName;
@SerializedName("customer_address")
@Expose
private String customerAddress;
@SerializedName("customer_primary_mobile")
@Expose
private String customerPrimaryMobile;
@SerializedName("customer_secondary_mobile")
@Expose
private String customerSecondaryMobile;
@SerializedName("customer_location")
@Expose
private Object customerLocation;
@SerializedName("customer_type_id")
@Expose
private Integer customerTypeId;

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}

public Integer getCustomerId() {
return customerId;
}

public void setCustomerId(Integer customerId) {
this.customerId = customerId;
}

public String getCustomerName() {
return customerName;
}

public void setCustomerName(String customerName) {
this.customerName = customerName;
}

public String getCustomerAddress() {
return customerAddress;
}

public void setCustomerAddress(String customerAddress) {
this.customerAddress = customerAddress;
}

public String getCustomerPrimaryMobile() {
return customerPrimaryMobile;
}

public void setCustomerPrimaryMobile(String customerPrimaryMobile) {
this.customerPrimaryMobile = customerPrimaryMobile;
}

public String getCustomerSecondaryMobile() {
return customerSecondaryMobile;
}

public void setCustomerSecondaryMobile(String customerSecondaryMobile) {
this.customerSecondaryMobile = customerSecondaryMobile;
}

public Object getCustomerLocation() {
return customerLocation;
}

public void setCustomerLocation(Object customerLocation) {
this.customerLocation = customerLocation;
}

public Integer getCustomerTypeId() {
return customerTypeId;
}

public void setCustomerTypeId(Integer customerTypeId) {
this.customerTypeId = customerTypeId;
}

}

then while you get response

UserDetail user= gson.fromJson("add json reponse here", UserDetail.class);

you can access all fields like user.getMessage(), user.getCustomerName()

How to parse a JSON response with retrofit

suppose you have response like that

 String json = {
"JHK":"One piece",
"LKJ":"Two pieces",
"OEN":"Three pieces"
}

then you can get a list of values ignoring keys like:

    ArrayList<String> arr = new ArrayList<>();
try {

JSONObject response = new JSONObject(json);
Iterator keys = response.keys();

while (keys.hasNext()) {
// loop to get the dynamic key
String currentKey = (String) keys.next();

// get the value of the dynamic key
String value = response.getJSONObject(currentKey).toString();
arr.add(value);
}


} catch (Throwable t) {
Log.e("My App", "Could not parse malformed JSON: \"" + json + "\"");
}

How to get raw json response of Retrofit in Kotlin?

It is pretty easy you just need to make your network calls function like this.

@FormUrlEncoded
@POST("Your URL")
fun myNetworkCall() : Call<ResponseBody>

The point here is your network call should return a Call of type ResponseBody. And from ResponseBody you can get the response in String format.

Now when you will call this function to perform the network call you will get the raw string response.

    MyApi().myNetworkCall().enqueue(object: Callback<ResponseBody>{
override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
//handle error here
}

override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
//your raw string response
val stringResponse = response.body()?.string()
}

})

Its pretty simple. Let me know if you want any other details. Hope this helps. Thank You

How to Parse Json in Kotlin Using Retrofit?

Status, message and data are all part of the response so you need to take care of that. For example this

data class AddUserResponse(
val `data`: UserInfo, //like you defined it
val message: String,
val status: Int,
val time: String
)

This means parameter and response are different so the RestApi needs to be changed to this

abstract fun addUser(@Body userData: UserInfo): Call<AddUserResponse>}

This in turn also change the types in the service like

class RestApiService
{
fun addUser(userData: UserInfo, onResult: (UserInfo?) -> Unit)
{
val retrofit = ServiceBuilder.buildService(RestApi::class.java)
retrofit.addUser(userData).enqueue(
object : Callback<AddUserResponse>
{
override fun onFailure(call: Call<AddUserResponse>, t: Throwable)
{
onResult(null)
}

override fun onResponse( call: Call<AddUserResponse>, response: Response<AddUserResponse>)
{
val addedUser = response.body()
Log.d("responsee",""+addedUser)
onResult(addedUser.data)
}
}
)
}
}

now in getQuotes you will have that it is a UserInfo object

    apiService.addUser(userInfo) {
val returnedUserInfo = it
}

Empty response body when parsing API with Retrofit and Gson


@FormUrlEncoded
@POST("user/login")
suspend fun login(
@Field("email") email:String,
@Field("password") password:String,
): Response<ContentResponse>



data class ContentResponse(
@SerializedName("content")
val loginResponse: LoginResponse
)

Maybe this can help you. you are getting data in content node so



Related Topics



Leave a reply



Submit