Retrofit Body isn't showing desired response from Nested JSON - java

I've been trying to connect an Android App to the Fitbit API using Retrofit however I'm struggling with getting a connection to a JSON with a nested user section. I've managed to get the classes set up however get Body: com.example.myapplication.User#6fe68c1 when requesting the body back.
Whilst learning about Retrofit I've had no problems with using however this seems to be different because of the "user" in the JSON.
Shortened JSON I'm working from
{
"user": {
"age": 23,
"avatar": "https://static0.fitbit.com/images/profile/defaultProfile_100.png",
"averageDailySteps": 2673,
"dateOfBirth": "1999-01-25",
"displayName": "Name.",
"features": {
"exerciseGoal": true
},
"fullName": "Full Name",
"gender": "MALE",
"glucoseUnit": "METRIC",
"height": 180.3,
"memberSince": "2022-02-28",
"startDayOfWeek": "MONDAY",
"strideLengthRunning": 123.10000000000001,
"weight": 72.5,
}
}
Fitbit Class
imports
#Generated("jsonschema2pojo")
public class Fitbit {
#SerializedName("user")
#Expose
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
User Class
imports
#Generated("jsonschema2pojo")
public class User {
#SerializedName("age")
#Expose
private Integer age;
#SerializedName("avatar")
#Expose
private String avatar;
#SerializedName("averageDailySteps")
#Expose
private Integer averageDailySteps;
#SerializedName("dateOfBirth")
#Expose
private String dateOfBirth;
#SerializedName("fullName")
#Expose
private String fullName;
#SerializedName("gender")
#Expose
private String gender;
#SerializedName("height")
#Expose
private Double height;
#SerializedName("memberSince")
#Expose
private String memberSince;
#SerializedName("startDayOfWeek")
#Expose
private String startDayOfWeek;
#SerializedName("strideLengthRunning")
#Expose
private Double strideLengthRunning;
#SerializedName("strideLengthWalking")
#Expose
private Double strideLengthWalking;
#SerializedName("timezone")
#Expose
private String timezone;
#SerializedName("waterUnitName")
#Expose
private String waterUnitName;
#SerializedName("weight")
#Expose
private Double weight;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public Integer getAverageDailySteps() {
return averageDailySteps;
}
public void setAverageDailySteps(Integer averageDailySteps) {
this.averageDailySteps = averageDailySteps;
}
public String getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Double getHeight() {
return height;
}
public void setHeight(Double height) {
this.height = height;
}
public String getMemberSince() {
return memberSince;
}
public void setMemberSince(String memberSince) {
this.memberSince = memberSince;
}
public String getStartDayOfWeek() {
return startDayOfWeek;
}
public void setStartDayOfWeek(String startDayOfWeek) {
this.startDayOfWeek = startDayOfWeek;
}
public Double getStrideLengthRunning() {
return strideLengthRunning;
}
public void setStrideLengthRunning(Double strideLengthRunning) {
this.strideLengthRunning = strideLengthRunning;
}
public Double getStrideLengthWalking() {
return strideLengthWalking;
}
public void setStrideLengthWalking(Double strideLengthWalking) {
this.strideLengthWalking = strideLengthWalking;
}
public String getTimezone() {
return timezone;
}
public void setTimezone(String timezone) {
this.timezone = timezone;
}
public String getWaterUnitName() {
return waterUnitName;
}
public void setWaterUnitName(String waterUnitName) {
this.waterUnitName = waterUnitName;
}
public Double getWeight() {
return weight;
}
public void setWeight(Double weight) {
this.weight = weight;
}
}
JsonPlaceholderAPI Interface Class
imports
public interface JsonPlaceholderAPI {
#Headers({"Authorization: Bearer bearercodeinserted"})
#GET("https://api.fitbit.com/1/user/-/profile.json")
Call<User> getUser();
}
MainActivity
public class MainActivity extends AppCompatActivity {
private TextView textViewResult;
private JsonPlaceholderAPI jsonPlaceholderAPI;
#Override
protected void onCreate(Bundle savedInstanceState) {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewResult = findViewById(R.id.text_view_result);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://jsonplaceholder.typicode.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
jsonPlaceholderAPI = retrofit.create(JsonPlaceholderAPI.class);
getUser();
}
private void getUser() {
Call<User> call = jsonPlaceholderAPI.getUser();
call.enqueue(new Callback<User>() {
#Override
public void onResponse(Call<User> call, Response<User> response) {
if (!response.isSuccessful()) {
textViewResult.setText("Code: " + response.code());
return;
}
textViewResult.setText("Body: " + response.body());
}
#Override
public void onFailure(Call<User> call, Throwable t) {
textViewResult.setText(t.getMessage());
}
});
}
}

Solution:
Change Call<User>() to Call<Fitbit>()
and response.body().getUser().toString()
If you want textViewResult.setText("Body: " + response.body()); to give you string representation of your User data you have to override toString() function on your User object. For example:
public class User {
#SerializedName("age")
#Expose
...
#Override
String toString() {
return "age: " + age + " avatar: " + avatar + ....;
}
}

Related

How to Fetch data from API using Retrofit in Android

I'm Trying to call API using retrofit in Android. Although I'm successfully able to api in response I'm getting Success Code = 200. But Apart from that Inside Json object Json array is null although while I'm trying to call same api in Postman I'm getting the desire result.
I'm trying to call using POST request
URL Request :- https://example.com/AD1/api/user/profile
I'm passing parameter in Body userid:- MFL176116
Below Postman
APIInterface.java
public interface APIInterface {
#POST("profile")
Call<ProfilePojo> getUserProfile(#Body ProfilePojo profilePojo);
}
ProfilePojo.java
public class ProfilePojo {
#SerializedName("message")
#Expose
private String message;
#SerializedName("code")
#Expose
private Integer code;
#SerializedName("user_data")
#Expose
private List<UserDatum> userData = new ArrayList();
private String userid;
public ProfilePojo(String userid) {
this.userid = userid;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<UserDatum> getUserData() {
return userData;
}
public void setUserData(List<UserDatum> userData) {
this.userData = userData;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public class UserDatum {
#SerializedName("id")
#Expose
private String id;
#SerializedName("username")
#Expose
private String username;
#SerializedName("password")
#Expose
private String password;
#SerializedName("under_id")
#Expose
private String underId;
#SerializedName("place_under_id")
#Expose
private String placeUnderId;
#SerializedName("mobile")
#Expose
private String mobile;
#SerializedName("side")
#Expose
private String side;
#SerializedName("email")
#Expose
private String email;
#SerializedName("status")
#Expose
private String status;
#SerializedName("member_name")
#Expose
private String memberName;
#SerializedName("package_id")
#Expose
private String packageId;
#SerializedName("package_id1")
#Expose
private String packageId1;
#SerializedName("avatar")
#Expose
private String avatar;
#SerializedName("gender")
#Expose
private Object gender;
#SerializedName("date_of_birth")
#Expose
private Object dateOfBirth;
#SerializedName("address_line1")
#Expose
private String addressLine1;
#SerializedName("address_line2")
#Expose
private String addressLine2;
#SerializedName("country")
#Expose
private String country;
#SerializedName("country_code")
#Expose
private String countryCode;
#SerializedName("state")
#Expose
private String state;
#SerializedName("city")
#Expose
private String city;
#SerializedName("pincode")
#Expose
private String pincode;
#SerializedName("pancard_no")
#Expose
private String pancardNo;
#SerializedName("adharcard_no")
#Expose
private String adharcardNo;
#SerializedName("franchaise_type")
#Expose
private String franchaiseType;
#SerializedName("franchise_id")
#Expose
private Object franchiseId;
#SerializedName("franchise_per")
#Expose
private Object franchisePer;
#SerializedName("franchise_status")
#Expose
private Object franchiseStatus;
#SerializedName("transaction_pass")
#Expose
private String transactionPass;
#SerializedName("id_proof")
#Expose
private Object idProof;
#SerializedName("address_proof")
#Expose
private Object addressProof;
#SerializedName("self_video")
#Expose
private String selfVideo;
#SerializedName("residential_proof")
#Expose
private String residentialProof;
#SerializedName("btc_address")
#Expose
private Object btcAddress;
#SerializedName("perfect_money")
#Expose
private Object perfectMoney;
#SerializedName("email_status")
#Expose
private String emailStatus;
#SerializedName("email_verify")
#Expose
private String emailVerify;
#SerializedName("created_on")
#Expose
private String createdOn;
#SerializedName("edited_on")
#Expose
private String editedOn;
#SerializedName("isDeleted")
#Expose
private String isDeleted;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUnderId() {
return underId;
}
public void setUnderId(String underId) {
this.underId = underId;
}
public String getPlaceUnderId() {
return placeUnderId;
}
public void setPlaceUnderId(String placeUnderId) {
this.placeUnderId = placeUnderId;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getSide() {
return side;
}
public void setSide(String side) {
this.side = side;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMemberName() {
return memberName;
}
public void setMemberName(String memberName) {
this.memberName = memberName;
}
public String getPackageId() {
return packageId;
}
public void setPackageId(String packageId) {
this.packageId = packageId;
}
public String getPackageId1() {
return packageId1;
}
public void setPackageId1(String packageId1) {
this.packageId1 = packageId1;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public Object getGender() {
return gender;
}
public void setGender(Object gender) {
this.gender = gender;
}
public Object getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Object dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getAddressLine1() {
return addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public String getAddressLine2() {
return addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCountryCode() {
return countryCode;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getPincode() {
return pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
public String getPancardNo() {
return pancardNo;
}
public void setPancardNo(String pancardNo) {
this.pancardNo = pancardNo;
}
public String getAdharcardNo() {
return adharcardNo;
}
public void setAdharcardNo(String adharcardNo) {
this.adharcardNo = adharcardNo;
}
public String getFranchaiseType() {
return franchaiseType;
}
public void setFranchaiseType(String franchaiseType) {
this.franchaiseType = franchaiseType;
}
public Object getFranchiseId() {
return franchiseId;
}
public void setFranchiseId(Object franchiseId) {
this.franchiseId = franchiseId;
}
public Object getFranchisePer() {
return franchisePer;
}
public void setFranchisePer(Object franchisePer) {
this.franchisePer = franchisePer;
}
public Object getFranchiseStatus() {
return franchiseStatus;
}
public void setFranchiseStatus(Object franchiseStatus) {
this.franchiseStatus = franchiseStatus;
}
public String getTransactionPass() {
return transactionPass;
}
public void setTransactionPass(String transactionPass) {
this.transactionPass = transactionPass;
}
public Object getIdProof() {
return idProof;
}
public void setIdProof(Object idProof) {
this.idProof = idProof;
}
public Object getAddressProof() {
return addressProof;
}
public void setAddressProof(Object addressProof) {
this.addressProof = addressProof;
}
public String getSelfVideo() {
return selfVideo;
}
public void setSelfVideo(String selfVideo) {
this.selfVideo = selfVideo;
}
public String getResidentialProof() {
return residentialProof;
}
public void setResidentialProof(String residentialProof) {
this.residentialProof = residentialProof;
}
public Object getBtcAddress() {
return btcAddress;
}
public void setBtcAddress(Object btcAddress) {
this.btcAddress = btcAddress;
}
public Object getPerfectMoney() {
return perfectMoney;
}
public void setPerfectMoney(Object perfectMoney) {
this.perfectMoney = perfectMoney;
}
public String getEmailStatus() {
return emailStatus;
}
public void setEmailStatus(String emailStatus) {
this.emailStatus = emailStatus;
}
public String getEmailVerify() {
return emailVerify;
}
public void setEmailVerify(String emailVerify) {
this.emailVerify = emailVerify;
}
public String getCreatedOn() {
return createdOn;
}
public void setCreatedOn(String createdOn) {
this.createdOn = createdOn;
}
public String getEditedOn() {
return editedOn;
}
public void setEditedOn(String editedOn) {
this.editedOn = editedOn;
}
public String getIsDeleted() {
return isDeleted;
}
public void setIsDeleted(String isDeleted) {
this.isDeleted = isDeleted;
}
}
}
Dashboard.java
private void getUserProfile() {
apiInterface = ApiLinks.getClient().create(APIInterface.class);
ProfilePojo profilePojo = new ProfilePojo("MFL176116");
Call<ProfilePojo> call = apiInterface.getUserProfile(profilePojo);
call.enqueue(new Callback<ProfilePojo>() {
#Override
public void onResponse(#NonNull Call<ProfilePojo> call, #NonNull Response<ProfilePojo> response) {
ProfilePojo profilePojo = response.body();
Toast.makeText(getApplicationContext(), "sucess", Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(#NonNull Call<ProfilePojo> call, #NonNull Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
After debugging the code can see Message is success, code =200, but userdata size ==0 please help me to get rid of this error
Check again the way that you are calling the api, even your userid is getting null, probably it's getting null in the user, but the response is 200 bc there was no error, simply no user with that id.

Android Java expected begin_object but was begin_array

Please Help me
This is my Models
Cases class
public class Cases {
#SerializedName("new")////this key value from json
#Expose
private String _new;
#SerializedName("active")
#Expose
private Integer active;
#SerializedName("critical")
#Expose
private Integer critical;
#SerializedName("recovered")
#Expose
private Integer recovered;
#SerializedName("1M_pop")
#Expose
private String _1MPop;
#SerializedName("total")
#Expose
private Integer total;
public String getNew() {
return _new;
}
public void setNew(String _new) {
this._new = _new;
}
public Integer getActive() {
return active;
}
public void setActive(Integer active) {
this.active = active;
}
public Integer getCritical() {
return critical;
}
public void setCritical(Integer critical) {
this.critical = critical;
}
public Integer getRecovered() {
return recovered;
}
public void setRecovered(Integer recovered) {
this.recovered = recovered;
}
public String get1MPop() {
return _1MPop;
}
public void set1MPop(String _1MPop) {
this._1MPop = _1MPop;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
}
Deaths class
public class Deaths {
#SerializedName("new")
#Expose
private String _new;
#SerializedName("1M_pop")
#Expose
private String _1MPop;
#SerializedName("total")
#Expose
private Integer total;
public String getNew() {
return _new;
}
public void setNew(String _new) {
this._new = _new;
}
public String get1MPop() {
return _1MPop;
}
public void set1MPop(String _1MPop) {
this._1MPop = _1MPop;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
}
public class Errors {//this is empty class
}
public class Parameters {//this is empty class
}
Tests class
public class Tests {
#SerializedName("1M_pop")
#Expose
private String _1MPop;
#SerializedName("total")
#Expose
private Integer total;
public String get1MPop() {
return _1MPop;
}
public void set1MPop(String _1MPop) {
this._1MPop = _1MPop;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
}
Response class
public class Response {
#SerializedName("continent")
#Expose
private String continent;
#SerializedName("country")
#Expose
private String country;
#SerializedName("population")
#Expose
private Integer population;
#SerializedName("cases")
#Expose
private Cases cases;
#SerializedName("deaths")
#Expose
private Deaths deaths;
#SerializedName("tests")
#Expose
private Tests tests;
#SerializedName("day")
#Expose
private String day;
#SerializedName("time")
#Expose
private String time;
public String getContinent() {
return continent;
}
public String getCountry() {
return country;
}
public Integer getPopulation() {
return population;
}
public Cases getCases() {
return cases;
}
public Deaths getDeaths() {
return deaths;
}
public Tests getTests() {
return tests;
}
public String getDay() {
return day;
}
public String getTime() {
return time;
}
}
Covid19Model class
public class Covid19Model {
#SerializedName("get")
#Expose
private String get;
#SerializedName("parameters")
#Expose
private Parameters parameters;
#SerializedName("errors")
#Expose
private Errors errors;
#SerializedName("results")
#Expose
private Integer results;
#SerializedName("response")
#Expose
private List<Response> response;
public String getGet() {
return get;
}
public void setGet(String get) {
this.get = get;
}
public Parameters getParameters() {
return parameters;
}
public void setParameters(Parameters parameters) {
this.parameters = parameters;
}
public Errors getErrors() {
return errors;
}
public void setErrors(Errors errors) {
this.errors = errors;
}
public Integer getResults() {
return results;
}
public void setResults(Integer results) {
this.results = results;
}
public List<Response> getResponse() {
return response;
}
public void setResponse(List<Response> response) {
this.response = response;
}
Covid19WebAPI interface
public interface Covid19WebApi {
#Headers({
"x-rapidapi-host:covid-193.p.rapidapi.com",
"x-rapidapi-key:fb818f40c4msh9ed8e59abf0e867p11b3bfjsn0900d33b78ef"//this is my rapidapi key
})
#GET("statistics")
Call<Covid19Model> getData();
}
MainActivity class
public class MainActivity extends AppCompatActivity {//This is my app MainActivity
List<Response> responses;
private static final String BASE_URL = "https://covid-193.p.rapidapi.com/";//this is covid api website
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create());//this is convert json
Retrofit retrofit = builder.build();
Covid19WebApi covid19WebApi = retrofit.create(Covid19WebApi.class);
Call<Covid19Model> call = covid19WebApi.getData();//this is call api interfacee method
call.enqueue(new Callback<Covid19Model>() {
#Override
public void onResponse(Call<Covid19Model> call, Response<Covid19Model> response) {
responses = response.body().getResponse();
for (Object data:responses){
System.out.println(data);//This my error (expected begin_array but was begin_object )
}
}
#Override
public void onFailure(Call<Covid19Model> call, Throwable t) {
Toast.makeText(MainActivity.this,t.getLocalizedMessage().toString(),Toast.LENGTH_LONG).show();//this is toast message failure
}
});
}
}
What is the problem
My error code ("expected begin_array but was begin_object")
I can't find out what the problem is in these codes and the data doesn't come in response and gives an error instead
As you can see in JSON response, errors and parameters are comes as List.
So please change fields to list in Covid19Model
#SerializedName("parameters")
#Expose
private List<Parameters> parameters;
#SerializedName("errors")
#Expose
private List<Errors> errors;

Iterating through the results of the JSON response - Android + Retrofit + Moshi

{
"data": [
{
"id": 4,
"customer_id": 3,
"service_type_id": 1,
"full_name": "Teja Babu S",
"email": "testemail#gmail.com",
camera_types": 1,
"dvr_types": 1,
"created_at": "2020-01-04 14:18:30",
"updated_at": "2020-01-04 14:18:30",
"camera_type": {
"id": 1,
"name": "Analogue hd",
"description": null,
"status": 1,
"deleted_at": null,
"created_at": "2020-01-04 08:03:45",
"updated_at": "2020-01-04 08:54:23"
},
"dvr_type": {
"id": 1,
"name": "XVR - nvr",
"description": "desc",
"status": 1,
"deleted_at": null,
"created_at": "2020-01-04 08:28:04",
"updated_at": "2020-01-04 08:57:17"
}
}
]
}
I am using the http://www.jsonschema2pojo.org/ for converion. I am not pasting the result to keep the question simple.
package - package
com.tesmachino.saycure.entities.OrderHistory.OrderDetail;
ClassName - OrderDetailsResponse
Target language: Java
Source type: JSON
Annotation style: Moshi
I would like to access the Name from Both camera_type and dvr_type
I am using Moshi + retrofit
OrderDetail
package com.tesmachino.saycure;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.tesmachino.saycure.Auth.TokenManager;
import com.tesmachino.saycure.entities.OrderHistory.OrderDetail.OrderDetailsResponse;
import com.tesmachino.saycure.entities.OrderHistory.OrderHistoryResponse;
import com.tesmachino.saycure.entities.UserDetails.UserDetailsGetResponse;
import com.tesmachino.saycure.network.ApiService;
import com.tesmachino.saycure.network.RetrofitBuilder;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class OrderDetail extends AppCompatActivity {
ApiService service;
TokenManager tokenManager;
Call<OrderDetailsResponse> call;
private static final String TAG = "OrderDetail";
#BindView(R.id.orderdetails_id)
TextView orderId;
#BindView(R.id.orderdetails_client_name)
TextView orderDetailsClientName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_detail);
ButterKnife.bind(this);
tokenManager = TokenManager.getInstance(getSharedPreferences("prefs", MODE_PRIVATE));
service = RetrofitBuilder.createServiceWithAuth(ApiService.class, tokenManager);
}
#Override
protected void onResume() {
//Get the Data from the Intent
if (getIntent().hasExtra("order_id")) {
int order_id = getIntent().getIntExtra("order_id", 1);
Log.d(TAG, "IntentWorking" + order_id);
call = service.orderDetails(order_id);
call.enqueue(new Callback<OrderDetailsResponse>() {
#Override
public void onResponse(Call<OrderDetailsResponse> call, Response<OrderDetailsResponse> response) {
OrderDetailsResponse orderDetails = response.body();
if (orderDetails != null){
}
Log.w(TAG, "onResponse123: " + orderDetails.getData().get(0).getId());
Toast.makeText(OrderDetail.this, "" + response.body().toString(), Toast.LENGTH_SHORT).show();
orderId.setText(String.valueOf(orderDetails.getData().get(0).getId()));
orderDetailsClientName.setText(orderDetails.getData().get(0).getFullName());
Log.w(TAG, "onResponse45321: "+ orderDetails.getData().get(0).getCameraType());
}
#Override
public void onFailure(Call<OrderDetailsResponse> call, Throwable t) {
Log.w(TAG, "onFailure: " + t.getMessage());
Toast.makeText(OrderDetail.this, "Failure" + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(this, "There seems to be an error while fetching the Order Id. Please Try Again", Toast.LENGTH_SHORT).show();
}
super.onResume();
}
}
OrderDetailsResponse
package com.tesmachino.saycure.entities.OrderHistory.OrderDetail;
import com.squareup.moshi.Json;
import org.apache.commons.lang3.builder.ToStringBuilder;
import java.util.List;
public class OrderDetailsResponse {
#Json(name = "data")
private List<OrderDetailsGet> data = null;
public List<OrderDetailsGet> getData() {
return data;
}
public void setData(List<OrderDetailsGet> data) {
this.data = data;
}
#Override
public String toString() {
return new ToStringBuilder(this).append("data", data).toString();
}
}
OrderDetailsGet
package com.tesmachino.saycure.entities.OrderHistory.OrderDetail;
import com.squareup.moshi.Json;
import org.apache.commons.lang3.builder.ToStringBuilder;
public class OrderDetailsGet {
#Json(name = "id")
private Integer id;
#Json(name = "customer_id")
private Integer customerId;
#Json(name = "service_type_id")
private Integer serviceTypeId;
#Json(name = "full_name")
private String fullName;
#Json(name = "email")
private String email;
#Json(name = "address_line_1")
private String addressLine1;
#Json(name = "address_line_2")
private String addressLine2;
#Json(name = "phone_no")
private String phoneNo;
#Json(name = "alternate_phone_no")
private Object alternatePhoneNo;
#Json(name = "land_mark")
private Object landMark;
#Json(name = "area")
private Object area;
#Json(name = "district")
private String district;
#Json(name = "city")
private String city;
#Json(name = "state")
private String state;
#Json(name = "pincode")
private Integer pincode;
#Json(name = "type_of_property")
private Integer typeOfProperty;
#Json(name = "camera_types")
private Integer cameraTypes;
#Json(name = "no_of_cameras")
private Integer noOfCameras;
#Json(name = "dvr_types")
private Integer dvrTypes;
#Json(name = "dvr_channel")
private Integer dvrChannel;
#Json(name = "notes")
private Object notes;
#Json(name = "deleted_at")
private Object deletedAt;
#Json(name = "created_at")
private String createdAt;
#Json(name = "updated_at")
private String updatedAt;
#Json(name = "camera_type")
private CameraType cameraType;
#Json(name = "dvr_type")
private DvrType dvrType;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getCustomerId() {
return customerId;
}
public void setCustomerId(Integer customerId) {
this.customerId = customerId;
}
public Integer getServiceTypeId() {
return serviceTypeId;
}
public void setServiceTypeId(Integer serviceTypeId) {
this.serviceTypeId = serviceTypeId;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddressLine1() {
return addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public String getAddressLine2() {
return addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
public String getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
public Object getAlternatePhoneNo() {
return alternatePhoneNo;
}
public void setAlternatePhoneNo(Object alternatePhoneNo) {
this.alternatePhoneNo = alternatePhoneNo;
}
public Object getLandMark() {
return landMark;
}
public void setLandMark(Object landMark) {
this.landMark = landMark;
}
public Object getArea() {
return area;
}
public void setArea(Object area) {
this.area = area;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Integer getPincode() {
return pincode;
}
public void setPincode(Integer pincode) {
this.pincode = pincode;
}
public Integer getTypeOfProperty() {
return typeOfProperty;
}
public void setTypeOfProperty(Integer typeOfProperty) {
this.typeOfProperty = typeOfProperty;
}
public Integer getCameraTypes() {
return cameraTypes;
}
public void setCameraTypes(Integer cameraTypes) {
this.cameraTypes = cameraTypes;
}
public Integer getNoOfCameras() {
return noOfCameras;
}
public void setNoOfCameras(Integer noOfCameras) {
this.noOfCameras = noOfCameras;
}
public Integer getDvrTypes() {
return dvrTypes;
}
public void setDvrTypes(Integer dvrTypes) {
this.dvrTypes = dvrTypes;
}
public Integer getDvrChannel() {
return dvrChannel;
}
public void setDvrChannel(Integer dvrChannel) {
this.dvrChannel = dvrChannel;
}
public Object getNotes() {
return notes;
}
public void setNotes(Object notes) {
this.notes = notes;
}
public Object getDeletedAt() {
return deletedAt;
}
public void setDeletedAt(Object deletedAt) {
this.deletedAt = deletedAt;
}
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public String getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
}
public CameraType getCameraType() {
return cameraType;
}
public void setCameraType(CameraType cameraType) {
this.cameraType = cameraType;
}
public DvrType getDvrType() {
return dvrType;
}
public void setDvrType(DvrType dvrType) {
this.dvrType = dvrType;
}
#Override
public String toString() {
return new ToStringBuilder(this).append("id", id).append("customerId", customerId).append("serviceTypeId", serviceTypeId).append("fullName", fullName).append("email", email).append("addressLine1", addressLine1).append("addressLine2", addressLine2).append("phoneNo", phoneNo).append("alternatePhoneNo", alternatePhoneNo).append("landMark", landMark).append("area", area).append("district", district).append("city", city).append("state", state).append("pincode", pincode).append("typeOfProperty", typeOfProperty).append("cameraTypes", cameraTypes).append("noOfCameras", noOfCameras).append("dvrTypes", dvrTypes).append("dvrChannel", dvrChannel).append("notes", notes).append("deletedAt", deletedAt).append("createdAt", createdAt).append("updatedAt", updatedAt).append("cameraType", cameraType).append("dvrType", dvrType).toString();
}
}
If you are just trying to the the name from camera_type and dvr_type, you can do:
//This assumes that you have a getCameraType & getDvrTypes method in your OrderDetailsGet class
String camera_name = orderDetails.getData().get(0).getCameraType().getName()
String dvr_name = orderDetails.getData().get(0).getDvrTypes().getName()

Retrofit with Gson Response.body() not working

I'am trying to parse data to a recyclerview, i had some problems about expecting JSONArray/JSONObject that i fixed with some help, but this moment I am a little bit lost in what to do in the Onresponse, the original - generatePhonesList(response.body()) isnt working.
this is my json and i am trying to parse the data inside the array results[] :
{
"success": true,
"metadata": {
"sort": "POPULARITY",
"total_products": 20,
"title": "Phones & Tablets",
"results": [
{
"sku": "1",
"name": "Samsung Galaxy S9",
"brand": "Samsung",
"max_saving_percentage": 30,
"price": 53996,
"special_price": 37990,
"image": "https://cdn2.gsmarena.com/vv/bigpic/samsung-galaxy-s9-.jpg",
"rating_average": 5
},
MainActivity (CALL and Recyclerview creation) :
GetPhoneDataService service = RetrofitInstance.getRetrofitInstance().create(GetPhoneDataService.class);
Call<APIReponse> call = service.getAllPhones();
call.enqueue(new Callback<APIReponse>() {
#Override
public void onResponse(Call<APIReponse> call, Response<APIReponse> response) {
generatePhonesList(response.body());
}
#Override
public void onFailure(Call<APIReponse> call, Throwable t) {
Log.e("eee" , "" + t.getMessage());
}
});
}
private void generatePhonesList(List<Result> phonesList){
recyclerView = findViewById(R.id.recyclerView);
adapter = new PhonesAdapter(phonesList,this);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
}
this is the POJO Class's created in jsonschema2pojo :
public class APIReponse {
#SerializedName("success")
#Expose
private Boolean success;
#SerializedName("metadata")
#Expose
private Metadata metadata;
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public Metadata getMetadata() {
return metadata;
}
public void setMetadata(Metadata metadata) {
this.metadata = metadata;
}
}
2 class
public class MetaData {
#SerializedName("sort")
#Expose
private String sort;
#SerializedName("total_products")
#Expose
private Integer totalProducts;
#SerializedName("title")
#Expose
private String title;
#SerializedName("results")
#Expose
private List<Result> results = null;
public String getSort() {
return sort;
}
public void setSort(String sort) {
this.sort = sort;
}
public Integer getTotalProducts() {
return totalProducts;
}
public void setTotalProducts(Integer totalProducts) {
this.totalProducts = totalProducts;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<Result> getResults() {
return results;
}
public void setResults(List<Result> results) {
this.results = results;
}
}
3 class:
public class Result {
#SerializedName("sku")
#Expose
private String sku;
#SerializedName("name")
#Expose
private String name;
#SerializedName("brand")
#Expose
private String brand;
#SerializedName("max_saving_percentage")
#Expose
private Integer maxSavingPercentage;
#SerializedName("price")
#Expose
private Integer price;
#SerializedName("special_price")
#Expose
private Integer specialPrice;
#SerializedName("image")
#Expose
private String image;
#SerializedName("rating_average")
#Expose
private Integer ratingAverage;
public String getSku() {
return sku;
}
public void setSku(String sku) {
this.sku = sku;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public Integer getMaxSavingPercentage() {
return maxSavingPercentage;
}
public void setMaxSavingPercentage(Integer maxSavingPercentage) {
this.maxSavingPercentage = maxSavingPercentage;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
public Integer getSpecialPrice() {
return specialPrice;
}
public void setSpecialPrice(Integer specialPrice) {
this.specialPrice = specialPrice;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public Integer getRatingAverage() {
return ratingAverage;
}
public void setRatingAverage(Integer ratingAverage) {
this.ratingAverage = ratingAverage;
}
}
You are passing the APIReponse model to the generatePhonesList(List<Result> phonesList) function. You need to pass only the list of results in this function.
Replace this:
generatePhonesList(response.body());
with:
generatePhonesList(response.body().getMetadata().getResults());
Here getMetadata() and getResults() are the getter functions of metadata model and List.
If you pay close attention response.body() will provide you with class APIResponse. But you need is List<Result>. To achieve this, try response.body().getMetadata().getResults()
This should give you the desired output.

How to post a JSON array using retrofit 2?

How to post JSON array using retrofit2 in Android?
here i attatch format of data
{
"lat": 11.024,
"lon": 75.054,
"maxdistance": 5000,
"amintyArray": [
"5ad251cfe601aa22a8f48d98",
"5ad251dae601aa22a8f48d99",
"5ad251ece601aa22a8f48d9a"
],
"starArray": [
"5ad252b1e601aa22a8f48db1"
]
}
pojo class like blow..
public class Example {
#SerializedName("lat")
#Expose
private Double lat;
#SerializedName("lon")
#Expose
private Double lon;
#SerializedName("maxdistance")
#Expose
private Integer maxdistance;
#SerializedName("amintyArray")
#Expose
private List<String> amintyArray = null;
#SerializedName("starArray")
#Expose
private List<String> starArray = null;
public Double getLat() {
return lat;
}
public void setLat(Double lat) {
this.lat = lat;
}
public Double getLon() {
return lon;
}
public void setLon(Double lon) {
this.lon = lon;
}
public Integer getMaxdistance() {
return maxdistance;
}
public void setMaxdistance(Integer maxdistance) {
this.maxdistance = maxdistance;
}
public List<String> getAmintyArray() {
return amintyArray;
}
public void setAmintyArray(List<String> amintyArray) {
this.amintyArray = amintyArray;
}
public List<String> getStarArray() {
return starArray;
}
public void setStarArray(List<String> starArray) {
this.starArray = starArray;
}
}
make request pojo class like below it define array or single value..
public class JsonData {
#SerializedName("createdAt")
private long createdAt;
#SerializedName("firstName")
private String firstName;
#SerializedName("password")
private String password;
#SerializedName("users")
private List<User> users;
public long getCreatedAt() {
return createdAt;
}
public void setCreatedAt(long createdAt) {
this.createdAt = createdAt;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
}
after that make api for requesting ..
#POST("linke")
Call<Response> passJsonData(#Body JsonData jsonData);
after insert data into Json data object then pass only json data.

Categories

Resources