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

{
"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()

Related

Retrofit Body isn't showing desired response from Nested JSON

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 + ....;
}
}

Output Spring Boot is reversed in Postman

My problem: when I do an #Post in Postman I get data back from the prices, but not kitten data.
I enter the following:
{
"name": "Frizzle",
"dateOfBirth": "2019-07-27",
"weight": 7.1,
"breed": "Birman",
"firstVaccination": "yes",
"secondVaccination": "yes",
"breedPrice": 8000,
"firstVaccinationPrice": 80.50,
"secondVaccinationPrice": 80.10
}
And this is what I get back in Postman:
{
"id": 3,
"name": null,
"dateOfBirth": null,
"weight": 0.0,
"breed": null,
"firstVaccination": null,
"secondVaccination": null,
"fileUpload": null,
"price": {
"id": 3,
"broadPrice": 8000.0,
"firstVaccinationPrice": 80.5,
"secondVaccinationPrice": 80.1,
"totalPrice": 8160.6
}
}
I've tried changing the code in several places, but I can't figure out why it outputs the price part and not the kitten data part. I want it to output the kitten data. So basically what I want is for him to reverse it, return data of the kittens and give data of the prices that are null.
My files look like this.
Kitten.java
import com.sun.istack.NotNull;
import javax.persistence.*;
import java.time.LocalDate;
#Entity
#Table(name = "kittens")
public class Kitten {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#NotNull
private String name;
#NotNull
#Column(name = "date_of_birth")
private LocalDate dateOfBirth;
#NotNull
#Column
private double weight;
#NotNull
#Column(name = "breed")
private String breed;
#Column(name = "first_vaccination")
private String firstVaccination;
#Column(name = "second_vaccination")
private String secondVaccination;
#OneToOne(mappedBy = "kitten")
private FileUpload fileUpload;
#OneToOne(fetch = FetchType.LAZY,
mappedBy = "kitten")
private Price price;
public Kitten(String name, LocalDate dateOfBirth, double weight, String breed, String firstVaccination, String secondVaccination) {
}
public Kitten() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public LocalDate getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(LocalDate dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public String getBreed() {
return breed;
}
public void setBreed(String breed) {
this.breed = breed;
}
public String getFirstVaccination() {
return firstVaccination;
}
public void setFirstVaccination(String firstVaccination) {
this.firstVaccination = firstVaccination;
}
public String getSecondVaccination() {
return secondVaccination;
}
public void setSecondVaccination(String secondVaccination) {
this.secondVaccination = secondVaccination;
}
public FileUpload getFileUpload() {
return fileUpload;
}
public void setFileUpload(FileUpload fileUpload) {
this.fileUpload = fileUpload;
}
public Price getPrice() {
return price;
}
public void setPrice(Price price) {
this.price = price;
}
}
Price.java
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.sun.istack.NotNull;
import javax.persistence.*;
#Entity
#Table(name = "prices")
public class Price {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#NotNull
#Column(name = "breed_price")
private double breedPrice;
#Column(name = "first_vaccination_price")
private double firstVaccinationPrice;
#Column(name = "second_vaccination_price")
private double secondVaccinationPrice;
#JsonIgnore
#OneToOne(fetch = FetchType.LAZY,
cascade = CascadeType.ALL,
orphanRemoval = true)
#JoinColumn(name = "kitten_id")
private Kitten kitten;
public Price() {
}
public Price(double breedPrice, double firstVaccinationPrice, double secondVaccinationPrice) {
this.breedPrice = breedPrice;
this.firstVaccinationPrice = firstVaccinationPrice;
this.secondVaccinationPrice = secondVaccinationPrice;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public double getBreedPrice() {
return breedPrice;
}
public void setBreedPrice(double breedPrice) {
this.breedPrice = breedPrice;
}
public double getFirstVaccinationPrice() {
return firstVaccinationPrice;
}
public void setFirstVaccinationPrice(double firstVaccinationPrice) {
this.firstVaccinationPrice = firstVaccinationPrice;
}
public double getSecondVaccinationPrice() {
return secondVaccinationPrice;
}
public void setSecondVaccinationPrice(double secondVaccinationPrice) {
this.secondVaccinationPrice = secondVaccinationPrice;
}
public Kitten getKitten() {
return kitten;
}
public void setKitten(Kitten kitten) {
this.kitten = kitten;
}
public Double getTotalPrice() {
return this.getBreedPrice() + this.getFirstVaccinationPrice() + this.getSecondVaccinationPrice();
}
}
KittenBuilder.java
import nl.danielle.cattery.payload.KittenRequest;
import java.time.LocalDate;
public class KittenBuilder {
//Kitten
private String name;
private LocalDate dateOfBirth;
private double weight;
private String breed;
private String firstVaccination;
private String secondVaccination;
//Price
private double breedPrice;
private double firstVaccinationPrice;
private double secondVaccinationPrice;
public KittenBuilder(KittenRequest kittenRequest) {
this.name = kittenRequest.getName();
this.dateOfBirth = kittenRequest.getDateOfBirth();
this.weight = kittenRequest.getWeight();
this.breed = kittenRequest.getBreed();
this.firstVaccination = kittenRequest.getFirstVaccination();
this.secondVaccination = kittenRequest.getSecondVaccination();
this.breedPrice = kittenRequest.getBreedPrice();
this.firstVaccinationPrice = kittenRequest.getFirstVaccinationPrice();
this.secondVaccinationPrice = kittenRequest.getSecondVaccinationPrice();
}
public Kitten buildKitten() {
return new Kitten(name, dateOfBirth, weight, breed, firstVaccination, secondVaccination);
}
public Price buildPrice() {
return new Price(breedPrice, firstVaccinationPrice, secondVaccinationPrice);
}
}
KittenRequest.java
import com.sun.istack.NotNull;
import java.time.LocalDate;
public class KittenRequest {
//Kitten
#NotNull
private String name;
#NotNull
private LocalDate dateOfBirth;
#NotNull
private double weight;
#NotNull
private String breed;
private String firstVaccination;
private String secondVaccination;
//Price
#NotNull
private double breedPrice;
private double firstVaccinationPrice;
private double secondVaccinationPrice;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public LocalDate getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(LocalDate dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public String getBreed() {
return breed;
}
public void setBreed(String breed) {
this.breed = breed;
}
public String getFirstVaccination() {
return firstVaccination;
}
public void setFirstVaccination(String firstVaccination) {
this.firstVaccination = firstVaccination;
}
public String getSecondVaccination() {
return secondVaccination;
}
public void setSecondVaccination(String secondVaccination) {
this.secondVaccination = secondVaccination;
}
public double getBreedPrice() {
return breedPrice;
}
public void setBreedPrice(double breedPrice) {
this.breedPrice = breedPrice;
}
public double getFirstVaccinationPrice() {
return firstVaccinationPrice;
}
public void setFirstVaccinationPrice(double firstVaccinationPrice) {
this.firstVaccinationPrice = firstVaccinationPrice;
}
public double getSecondVaccinationPrice() {
return secondVaccinationPrice;
}
public void setSecondVaccinationPrice(double secondVaccinationPrice) {
this.secondVaccinationPrice = secondVaccinationPrice;
}
}
KittenController.java
import nl.danielle.cattery.model.FileUpload;
import nl.danielle.cattery.payload.KittenRequest;
import nl.danielle.cattery.payload.ResponseMessage;
import nl.danielle.cattery.service.FileStorageServiceImpl;
import nl.danielle.cattery.service.KittenService;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import java.net.URI;
#RestController
#RequestMapping(value = "/kittens")
public class KittenController {
final KittenService kittenService;
final FileStorageServiceImpl storageService;
public KittenController(KittenService kittenService, FileStorageServiceImpl storageService) {
this.kittenService = kittenService;
this.storageService = storageService;
}
#GetMapping(value = "")
public ResponseEntity<Object> getKittens() {
return ResponseEntity.ok().body(kittenService.getKittens());
}
#GetMapping(value = "/{id}")
public ResponseEntity<Object> getKitten(#PathVariable("id") long id) {
return ResponseEntity.ok().body(kittenService.getKittenById(id));
}
#PostMapping(value = "/add")
public ResponseEntity<Object> saveKitten(#RequestBody KittenRequest kitten) {
long newId = kittenService.saveKitten(kitten);
URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
.buildAndExpand(newId).toUri();
return ResponseEntity.created(location).build();
}
#PutMapping(value = "/{id}")
public ResponseEntity<Object> updateKitten(#PathVariable("id") long id, #RequestBody KittenRequest kitten) {
kittenService.updateKitten(id, kitten);
return ResponseEntity.noContent().build();
}
#PutMapping(value = "/{id}/price")
public ResponseEntity<Object> updatePrice(#PathVariable("id") long id, #RequestBody KittenRequest price) {
kittenService.updatePrice(id, price);
return ResponseEntity.noContent().build();
}
#DeleteMapping(value = "/{id}")
public ResponseEntity<Object> deleteKitten(#PathVariable("id") long id) {
kittenService.deleteKitten(id);
return ResponseEntity.noContent().build();
}
#PostMapping("/upload/kittenid/{id}")
public ResponseEntity<ResponseMessage> uploadFile(#PathVariable long id, #RequestParam("file") MultipartFile file) {
try {
storageService.store(file, id);
String message = "Uploaded the file successfully: " + file.getOriginalFilename();
return ResponseEntity.status(HttpStatus.OK).body(new ResponseMessage(message));
} catch (Exception e) {
String message = "Could not upload the file: " + file.getOriginalFilename() + "!";
return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(new ResponseMessage(message));
}
}
#GetMapping("/download/{id}")
public ResponseEntity<byte[]> getFileById(#PathVariable("id") String id) {
FileUpload fileUpload = storageService.getFileById(id);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileUpload.getName() + "\"")
.body(fileUpload.getData());
}
}
KittenService.java
package nl.danielle.cattery.service;
import nl.danielle.cattery.exceptions.DatabaseErrorException;
import nl.danielle.cattery.exceptions.RecordNotFoundException;
import nl.danielle.cattery.model.Kitten;
import nl.danielle.cattery.model.KittenBuilder;
import nl.danielle.cattery.model.Price;
import nl.danielle.cattery.payload.KittenRequest;
import nl.danielle.cattery.repository.KittenRepository;
import nl.danielle.cattery.repository.PriceRepository;
import org.springframework.stereotype.Service;
import java.util.Collection;
#Service
public class KittenServiceImpl implements KittenService {
final KittenRepository kittenRepository;
final PriceRepository priceRepository;
public KittenServiceImpl(KittenRepository kittenRepository, PriceRepository priceRepository) {
this.kittenRepository = kittenRepository;
this.priceRepository = priceRepository;
}
#Override
public Collection<Kitten> getKittens() {
return kittenRepository.findAll();
}
#Override
public Kitten getKittenById(long id) {
if (!kittenRepository.existsById(id)) {
throw new RecordNotFoundException();
}
return kittenRepository.findById(id).orElse(null);
}
#Override
public long saveKitten(KittenRequest kittenRequest) {
Kitten newKitten = new KittenBuilder(kittenRequest).buildKitten();
Price newPrice = new KittenBuilder(kittenRequest).buildPrice();
Price savedPrice = priceRepository.save(newPrice);
newKitten.setPrice(savedPrice);
newPrice.setKitten(newKitten);
return kittenRepository.save(newKitten).getId();
}
#Override
public void updateKitten(long id, KittenRequest kitten) {
if (kittenRepository.existsById(id)) {
try {
Kitten existingKitten = kittenRepository.findById(id).orElse(null);
existingKitten.setName(kitten.getName());
existingKitten.setDateOfBirth(kitten.getDateOfBirth());
existingKitten.setWeight(kitten.getWeight());
existingKitten.setBreed(kitten.getBreed());
existingKitten.setFirstVaccination(kitten.getFirstVaccination());
existingKitten.setSecondVaccination(kitten.getSecondVaccination());
kittenRepository.save(existingKitten);
} catch (Exception ex) {
throw new DatabaseErrorException();
}
} else {
throw new RecordNotFoundException();
}
}
#Override
public void updatePrice(long id, KittenRequest price) {
if (priceRepository.existsById(id)) {
try {
Price existingPrice = priceRepository.findById(id).orElse(null);
existingPrice.setBreedPrice(price.getBreedPrice());
existingPrice.setFirstVaccinationPrice(price.getFirstVaccinationPrice());
existingPrice.setSecondVaccinationPrice(price.getSecondVaccinationPrice());
priceRepository.save(existingPrice);
} catch (Exception ex) {
throw new DatabaseErrorException();
}
} else {
throw new RecordNotFoundException();
}
}
#Override
public void deleteKitten(long id) {
kittenRepository.deleteById(id);
}
}
I have a lot to say about your code here, but let's see what's the main problem here. The problem is simple if you look at your KittenBuilder you create a Kitten using this builder but your Kitten constructor is empty.
public Kitten(String name, LocalDate dateOfBirth, double weight, String breed, String firstVaccination, String secondVaccination) {
this.name = name;
this.dateOfBirth = dateOfBirth;
this.weight = weight;
this.breed = breed;
this.firstVaccination = firstVaccination;
this.secondVaccination = secondVaccination;
}
This will populate the Kitten object and you're ready to go.
Some advices about your code
If you wonder why it's saving the null values when you specified the null constraints is that recent version of spring boot don't include the validation starter in the web starter, you have to include it yourself.
In you pom.xml add the following dependecy:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
And you have to include the annotation #Transactional to your services to make your operations atomic, for example in your create kitten method you want to persist the price and the kitten atomically.
#Service
#Transactional
class KittenServiceImpl implementes ...
And one the best practices also, is to not use your entites directly in your controllers, use DTO (Data Transfer Object), so you map the properties you want from your entity to your DTO (this way you can include only your kitten properties and leave the price entity).
And last bonus:
public Kitten getKittenById(long id) {
if (!kittenRepository.existsById(id)) {
throw new RecordNotFoundException("");
}
return kittenRepository.findById(id).orElse(null);
}
This can be simplified to:
public Kitten getKittenById(long id) {
return kittenRepository.findById(id).orElseThrow(() -> new RecordNotFoundException());
}

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `response` out of START_ARRAY token

I keep getting this response when im trying to execute my retrofit call for this reseponse:
package retrofit.responses;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"id",
"version",
"createdDate",
"modifiedDate",
"rie",
"line1",
"line2",
"line3",
"line4",
"line5",
"county",
"postCode",
"country",
"primary",
"accomodationStatus",
"addressType",
"effectiveFrom",
"effectiveTo",
"secured"
})
#Generated("jsonschema2pojo")
public class ReferralResponse {
#JsonProperty("id")
private Object id;
#JsonProperty("version")
private Integer version;
#JsonProperty("createdDate")
private Object createdDate;
#JsonProperty("modifiedDate")
private Object modifiedDate;
#JsonProperty("rie")
private Boolean rie;
#JsonProperty("line1")
private String line1;
#JsonProperty("line2")
private Object line2;
#JsonProperty("line3")
private Object line3;
#JsonProperty("line4")
private String line4;
#JsonProperty("line5")
private Object line5;
#JsonProperty("county")
private Object county;
#JsonProperty("postCode")
private String postCode;
#JsonProperty("country")
private Object country;
#JsonProperty("primary")
private Boolean primary;
#JsonProperty("accomodationStatus")
private AccomodationStatus accomodationStatus;
#JsonProperty("addressType")
private Object addressType;
#JsonProperty("effectiveFrom")
private Long effectiveFrom;
#JsonProperty("effectiveTo")
private Object effectiveTo;
#JsonProperty("secured")
private Boolean secured;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("id")
public Object getId() {
return id;
}
#JsonProperty("id")
public void setId(Object id) {
this.id = id;
}
#JsonProperty("version")
public Integer getVersion() {
return version;
}
#JsonProperty("version")
public void setVersion(Integer version) {
this.version = version;
}
#JsonProperty("createdDate")
public Object getCreatedDate() {
return createdDate;
}
#JsonProperty("createdDate")
public void setCreatedDate(Object createdDate) {
this.createdDate = createdDate;
}
#JsonProperty("modifiedDate")
public Object getModifiedDate() {
return modifiedDate;
}
#JsonProperty("modifiedDate")
public void setModifiedDate(Object modifiedDate) {
this.modifiedDate = modifiedDate;
}
#JsonProperty("rie")
public Boolean getRie() {
return rie;
}
#JsonProperty("rie")
public void setRie(Boolean rie) {
this.rie = rie;
}
#JsonProperty("line1")
public String getLine1() {
return line1;
}
#JsonProperty("line1")
public void setLine1(String line1) {
this.line1 = line1;
}
#JsonProperty("line2")
public Object getLine2() {
return line2;
}
#JsonProperty("line2")
public void setLine2(Object line2) {
this.line2 = line2;
}
#JsonProperty("line3")
public Object getLine3() {
return line3;
}
#JsonProperty("line3")
public void setLine3(Object line3) {
this.line3 = line3;
}
#JsonProperty("line4")
public String getLine4() {
return line4;
}
#JsonProperty("line4")
public void setLine4(String line4) {
this.line4 = line4;
}
#JsonProperty("line5")
public Object getLine5() {
return line5;
}
#JsonProperty("line5")
public void setLine5(Object line5) {
this.line5 = line5;
}
#JsonProperty("county")
public Object getCounty() {
return county;
}
#JsonProperty("county")
public void setCounty(Object county) {
this.county = county;
}
#JsonProperty("postCode")
public String getPostCode() {
return postCode;
}
#JsonProperty("postCode")
public void setPostCode(String postCode) {
this.postCode = postCode;
}
#JsonProperty("country")
public Object getCountry() {
return country;
}
#JsonProperty("country")
public void setCountry(Object country) {
this.country = country;
}
#JsonProperty("primary")
public Boolean getPrimary() {
return primary;
}
#JsonProperty("primary")
public void setPrimary(Boolean primary) {
this.primary = primary;
}
#JsonProperty("accomodationStatus")
public AccomodationStatus getAccomodationStatus() {
return accomodationStatus;
}
#JsonProperty("accomodationStatus")
public void setAccomodationStatus(AccomodationStatus accomodationStatus) {
this.accomodationStatus = accomodationStatus;
}
#JsonProperty("addressType")
public Object getAddressType() {
return addressType;
}
#JsonProperty("addressType")
public void setAddressType(Object addressType) {
this.addressType = addressType;
}
#JsonProperty("effectiveFrom")
public Long getEffectiveFrom() {
return effectiveFrom;
}
#JsonProperty("effectiveFrom")
public void setEffectiveFrom(Long effectiveFrom) {
this.effectiveFrom = effectiveFrom;
}
#JsonProperty("effectiveTo")
public Object getEffectiveTo() {
return effectiveTo;
}
#JsonProperty("effectiveTo")
public void setEffectiveTo(Object effectiveTo) {
this.effectiveTo = effectiveTo;
}
#JsonProperty("secured")
public Boolean getSecured() {
return secured;
}
#JsonProperty("secured")
public void setSecured(Boolean secured) {
this.secured = secured;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
and im trying to getID and use that in another call. This is an object that I am trying to turn into an integer an then use that in a seperate call again.
referralResponseResponse = call1.getReferral(token).execute();
int i = (int) referralResponseResponse.body().getId();
System.out.println("Int: " + i);
I should also note the json that I'm using this data from is very large so ive just used jsonpogo to extract this information to a java file and then use the parts that apply to me, I dont imagine i have to set up a java class for every part of the retruned json
Try to add following annotation for your POJO class:
#JsonIgnoreProperties(ignoreUnknown = true)

How to Convert JSON to POJO class?

I checked the following json, it is valid, But http://www.jsonschema2pojo.org/ is not converting it into POJO object so I can fetch values from it, I need "nameValuePairs" object in following model. Please help. Thanks in advance
[
"order-chat-1",
{
"nameValuePairs":{
"chat":{
"nameValuePairs":{
"id":19,
"order_id":6,
"sender_id":10,
"receiver_id":3,
"message":"Hi",
"is_read":0,
"created_at":"2018-10-19 16:23:28",
"updated_at":"2018-10-19 16:23:28",
"is_sender":false
}
},
"message":"Hello from chef",
"message_type":"Message",
"is_sender":false
}
}
]
Here is the code to put on http://www.jsonschema2pojo.org/
{
"type":"object",
"properties":{
"chat":{
"type":"object",
"properties":{
"nameValuePairs":{
"type":"object",
"properties":{
"id": {"type": "integer"},
"order_id":{"type": "integer"},
"sender_id":{"type": "integer"},
"receiver_id":{"type": "integer"},
"message":{"type": "string"},
"is_read":{"type": "integer"},
"created_at":{"type": "string"},
"updated_at":{"type": "string"},
"is_sender":{"type": "boolean"}
}
}
}
},
"message":{"type": "string"},
"message_type":{"type": "string"},
"is_sender":{"type": "boolean"}
}
}
That produces the following POJO's where Example.class is your root object, change the name as you want.
-----------------------------------com.example.Chat.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Chat {
#SerializedName("nameValuePairs")
#Expose
private NameValuePairs nameValuePairs;
public NameValuePairs getNameValuePairs() {
return nameValuePairs;
}
public void setNameValuePairs(NameValuePairs nameValuePairs) {
this.nameValuePairs = nameValuePairs;
}
public Chat withNameValuePairs(NameValuePairs nameValuePairs) {
this.nameValuePairs = nameValuePairs;
return this;
}
}
-----------------------------------com.example.Example.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("chat")
#Expose
private Chat chat;
#SerializedName("message")
#Expose
private String message;
#SerializedName("message_type")
#Expose
private String messageType;
#SerializedName("is_sender")
#Expose
private boolean isSender;
public Chat getChat() {
return chat;
}
public void setChat(Chat chat) {
this.chat = chat;
}
public Example withChat(Chat chat) {
this.chat = chat;
return this;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Example withMessage(String message) {
this.message = message;
return this;
}
public String getMessageType() {
return messageType;
}
public void setMessageType(String messageType) {
this.messageType = messageType;
}
public Example withMessageType(String messageType) {
this.messageType = messageType;
return this;
}
public boolean isIsSender() {
return isSender;
}
public void setIsSender(boolean isSender) {
this.isSender = isSender;
}
public Example withIsSender(boolean isSender) {
this.isSender = isSender;
return this;
}
}
-----------------------------------com.example.NameValuePairs.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class NameValuePairs {
#SerializedName("id")
#Expose
private int id;
#SerializedName("order_id")
#Expose
private int orderId;
#SerializedName("sender_id")
#Expose
private int senderId;
#SerializedName("receiver_id")
#Expose
private int receiverId;
#SerializedName("message")
#Expose
private String message;
#SerializedName("is_read")
#Expose
private int isRead;
#SerializedName("created_at")
#Expose
private String createdAt;
#SerializedName("updated_at")
#Expose
private String updatedAt;
#SerializedName("is_sender")
#Expose
private boolean isSender;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public NameValuePairs withId(int id) {
this.id = id;
return this;
}
public int getOrderId() {
return orderId;
}
public void setOrderId(int orderId) {
this.orderId = orderId;
}
public NameValuePairs withOrderId(int orderId) {
this.orderId = orderId;
return this;
}
public int getSenderId() {
return senderId;
}
public void setSenderId(int senderId) {
this.senderId = senderId;
}
public NameValuePairs withSenderId(int senderId) {
this.senderId = senderId;
return this;
}
public int getReceiverId() {
return receiverId;
}
public void setReceiverId(int receiverId) {
this.receiverId = receiverId;
}
public NameValuePairs withReceiverId(int receiverId) {
this.receiverId = receiverId;
return this;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public NameValuePairs withMessage(String message) {
this.message = message;
return this;
}
public int getIsRead() {
return isRead;
}
public void setIsRead(int isRead) {
this.isRead = isRead;
}
public NameValuePairs withIsRead(int isRead) {
this.isRead = isRead;
return this;
}
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public NameValuePairs withCreatedAt(String createdAt) {
this.createdAt = createdAt;
return this;
}
public String getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
}
public NameValuePairs withUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
return this;
}
public boolean isIsSender() {
return isSender;
}
public void setIsSender(boolean isSender) {
this.isSender = isSender;
}
public NameValuePairs withIsSender(boolean isSender) {
this.isSender = isSender;
return this;
}
}
It is valid from JavaScript prospective, but not form standard Java libraries such as GSON, Jackson or whatever www.jsonschema2pojo.org uses.
There are two things:
It is an Array on top
There are two different types in that array String and an Object
It can be converted only to Object[] or Collection<Object> (e.g.List, Set etc).
But to do that you have to have a custom Serializer/Deserializer.
I worked with another technique to resolve this, I converted this Object to String through Gson() and after that with subString method I removed the first 16 characters and the last character of the newly created string, then I Converted that String to POJO Object.

How can I set My Json Value in Adapter

I Am Having two JsonArray in Which there is JsonObject I have Got the String of each value but the problem is that when i am passing i into adapter I am getting indexOutofbound exeption because my value are getting Store in my object class so can any one help me how can i send my data to Object so that i can inflate to recyclerView.
private void callola() {
progressDialog = new ProgressDialog(CabBookingActivity.this);
progressDialog.setMessage("Loading ...");
progressDialog.setCancelable(false);
progressDialog.show();
final RequestQueue queue = Volley.newRequestQueue(CabBookingActivity.this);
String url = "https://www.reboundindia.com/app/application/ola/ride_estimate.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.setCancelable(true);
progressDialog.dismiss();
Log.e("sushil Call ola response", response);
try {
JSONObject mainObj = new JSONObject(response);
arrayList = new ArrayList<>();
String result = mainObj.getString("result");
int i, j;
ArrayList categoriess, Ride;
if (result.equals("606")) {
JSONObject message = mainObj.getJSONObject("message");
categories = message.getJSONArray("categories");
ride_estimate = message.getJSONArray("ride_estimate");
// JSONArray ride_estimate = message.getJSONArray("ride_estimate");
for (i = 0; i < categories.length(); i++) {
Log.e("sushil", String.valueOf(i));
jsonObject = categories.getJSONObject(i);
id = jsonObject.getString("id");
display_name = jsonObject.getString("display_name");
image = jsonObject.getString("image");
eta = jsonObject.getString("eta");
Log.e("OutPut", id + " " + eta + " " + image + " " + amount_min + " " + amount_max);
}
for (j = 0; j < ride_estimate.length(); j++) {
Log.e("sushil", String.valueOf(j));
rideestimate = ride_estimate.getJSONObject(j);
distance = rideestimate.getString("distance");
amount_min = rideestimate.getString("amount_min");
amount_max = rideestimate.getString("amount_max");
category = rideestimate.getString("category");
}
}
OlaUberModel olaUberModel = new OlaUberModel(category, display_name, amount_min, eta, image, amount_max);
arrayList.add(olaUberModel);
Log.e("sushil ride_estimate", distance + " " + amount_min + " " + amount_max);
AdapterOlaUber adapterOlaUber = new AdapterOlaUber(context, arrayList, CabBookingActivity.this);
recyclerView.setAdapter(adapterOlaUber);
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Log.e("error", error.toString());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("pickup_lat", "" + pickLat);
params.put("pickup_lng", "" + pickLong);
params.put("drop_lat", String.valueOf(dropLat));
params.put("drop_lng", String.valueOf(dropLong));
params.put("category", "all");
params.put("token", token);
Log.e("sushil param", String.valueOf(params));
return params;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
90000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(stringRequest);
}
Here is my JSONRESPONSE
{
"result":"606",
"message":{
"categories":[
{
"id":"micro",
"display_name":"Micro",
"currency":"INR",
"distance_unit":"kilometre",
"time_unit":"minute",
"eta":5,
"distance":"0.7",
"ride_later_enabled":"true",
"image":"http:\/\/d1foexe15giopy.cloudfront.net\/micro.png",
"cancellation_policy":{
"cancellation_charge":50,
"currency":"INR",
"cancellation_charge_applies_after_time":5,
"time_unit":"minute"
},
"fare_breakup":[
{
"type":"flat_rate",
"minimum_distance":0,
"minimum_time":0,
"base_fare":50,
"minimum_fare":60,
"cost_per_distance":6,
"waiting_cost_per_minute":0,
"ride_cost_per_minute":1.5,
"surcharge":[
],
"rates_lower_than_usual":false,
"rates_higher_than_usual":false
}
]
},
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ }
],
"ride_estimate":[
{
"category":"prime_play",
"distance":3.99,
"travel_time_in_minutes":30,
"amount_min":155,
"amount_max":163,
"discounts":{
"discount_type":null,
"discount_code":null,
"discount_mode":null,
"discount":0,
"cashback":0
}
},
{ },
{ },
{ },
{ },
{ },
{ },
{ }
]
}
}
My Problem is that how can send the data in model.
My Model Should contain data Like id,displayName,amountMin,eta,image,amountMax
First of all you need to make two different models for category and ride_estimate.Because they both are in different loops. Also try this
for (j = 0; j < ride_estimate.length(); j++) {
Log.e("sushil", String.valueOf(j));
rideestimate = ride_estimate.getJSONObject(j);
distance = rideestimate.getString("distance");
amount_min = rideestimate.getString("amount_min");
amount_max = rideestimate.getString("amount_max");
category = rideestimate.getString("category");
OlaUberModel olaUberModel = new OlaUberModel(category, display_name, amount_min, eta, image, amount_max);
arrayList.add(olaUberModel);
}
May be this would helpful for you..
Thanks!
replace
eta = jsonObject.getString("eta");
by
int eta = jsonObject.getInt("eta");
On the basis of id of any cab type "prime" you can fetch image. what say
create some class as per your data
-----------------------------------com.example.CancellationPolicy.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class CancellationPolicy {
#SerializedName("cancellation_charge")
#Expose
private Integer cancellationCharge;
#SerializedName("currency")
#Expose
private String currency;
#SerializedName("cancellation_charge_applies_after_time")
#Expose
private Integer cancellationChargeAppliesAfterTime;
#SerializedName("time_unit")
#Expose
private String timeUnit;
public Integer getCancellationCharge() {
return cancellationCharge;
}
public void setCancellationCharge(Integer cancellationCharge) {
this.cancellationCharge = cancellationCharge;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public Integer getCancellationChargeAppliesAfterTime() {
return cancellationChargeAppliesAfterTime;
}
public void setCancellationChargeAppliesAfterTime(Integer cancellationChargeAppliesAfterTime) {
this.cancellationChargeAppliesAfterTime = cancellationChargeAppliesAfterTime;
}
public String getTimeUnit() {
return timeUnit;
}
public void setTimeUnit(String timeUnit) {
this.timeUnit = timeUnit;
}
}
-----------------------------------com.example.Category.java-----------------------------------
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Category {
#SerializedName("id")
#Expose
private String id;
#SerializedName("display_name")
#Expose
private String displayName;
#SerializedName("currency")
#Expose
private String currency;
#SerializedName("distance_unit")
#Expose
private String distanceUnit;
#SerializedName("time_unit")
#Expose
private String timeUnit;
#SerializedName("eta")
#Expose
private Integer eta;
#SerializedName("distance")
#Expose
private String distance;
#SerializedName("ride_later_enabled")
#Expose
private String rideLaterEnabled;
#SerializedName("image")
#Expose
private String image;
#SerializedName("cancellation_policy")
#Expose
private CancellationPolicy cancellationPolicy;
#SerializedName("fare_breakup")
#Expose
private List<FareBreakup> fareBreakup = null;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public String getDistanceUnit() {
return distanceUnit;
}
public void setDistanceUnit(String distanceUnit) {
this.distanceUnit = distanceUnit;
}
public String getTimeUnit() {
return timeUnit;
}
public void setTimeUnit(String timeUnit) {
this.timeUnit = timeUnit;
}
public Integer getEta() {
return eta;
}
public void setEta(Integer eta) {
this.eta = eta;
}
public String getDistance() {
return distance;
}
public void setDistance(String distance) {
this.distance = distance;
}
public String getRideLaterEnabled() {
return rideLaterEnabled;
}
public void setRideLaterEnabled(String rideLaterEnabled) {
this.rideLaterEnabled = rideLaterEnabled;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public CancellationPolicy getCancellationPolicy() {
return cancellationPolicy;
}
public void setCancellationPolicy(CancellationPolicy cancellationPolicy) {
this.cancellationPolicy = cancellationPolicy;
}
public List<FareBreakup> getFareBreakup() {
return fareBreakup;
}
public void setFareBreakup(List<FareBreakup> fareBreakup) {
this.fareBreakup = fareBreakup;
}
}
-----------------------------------com.example.Discounts.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Discounts {
#SerializedName("discount_type")
#Expose
private Object discountType;
#SerializedName("discount_code")
#Expose
private Object discountCode;
#SerializedName("discount_mode")
#Expose
private Object discountMode;
#SerializedName("discount")
#Expose
private Integer discount;
#SerializedName("cashback")
#Expose
private Integer cashback;
public Object getDiscountType() {
return discountType;
}
public void setDiscountType(Object discountType) {
this.discountType = discountType;
}
public Object getDiscountCode() {
return discountCode;
}
public void setDiscountCode(Object discountCode) {
this.discountCode = discountCode;
}
public Object getDiscountMode() {
return discountMode;
}
public void setDiscountMode(Object discountMode) {
this.discountMode = discountMode;
}
public Integer getDiscount() {
return discount;
}
public void setDiscount(Integer discount) {
this.discount = discount;
}
public Integer getCashback() {
return cashback;
}
public void setCashback(Integer cashback) {
this.cashback = cashback;
}
}
-----------------------------------com.example.Example.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("result")
#Expose
private String result;
#SerializedName("message")
#Expose
private Message message;
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public Message getMessage() {
return message;
}
public void setMessage(Message message) {
this.message = message;
}
}
-----------------------------------com.example.FareBreakup.java-----------------------------------
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class FareBreakup {
#SerializedName("type")
#Expose
private String type;
#SerializedName("minimum_distance")
#Expose
private Integer minimumDistance;
#SerializedName("minimum_time")
#Expose
private Integer minimumTime;
#SerializedName("base_fare")
#Expose
private Integer baseFare;
#SerializedName("minimum_fare")
#Expose
private Integer minimumFare;
#SerializedName("cost_per_distance")
#Expose
private Integer costPerDistance;
#SerializedName("waiting_cost_per_minute")
#Expose
private Integer waitingCostPerMinute;
#SerializedName("ride_cost_per_minute")
#Expose
private Double rideCostPerMinute;
#SerializedName("surcharge")
#Expose
private List<Object> surcharge = null;
#SerializedName("rates_lower_than_usual")
#Expose
private Boolean ratesLowerThanUsual;
#SerializedName("rates_higher_than_usual")
#Expose
private Boolean ratesHigherThanUsual;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Integer getMinimumDistance() {
return minimumDistance;
}
public void setMinimumDistance(Integer minimumDistance) {
this.minimumDistance = minimumDistance;
}
public Integer getMinimumTime() {
return minimumTime;
}
public void setMinimumTime(Integer minimumTime) {
this.minimumTime = minimumTime;
}
public Integer getBaseFare() {
return baseFare;
}
public void setBaseFare(Integer baseFare) {
this.baseFare = baseFare;
}
public Integer getMinimumFare() {
return minimumFare;
}
public void setMinimumFare(Integer minimumFare) {
this.minimumFare = minimumFare;
}
public Integer getCostPerDistance() {
return costPerDistance;
}
public void setCostPerDistance(Integer costPerDistance) {
this.costPerDistance = costPerDistance;
}
public Integer getWaitingCostPerMinute() {
return waitingCostPerMinute;
}
public void setWaitingCostPerMinute(Integer waitingCostPerMinute) {
this.waitingCostPerMinute = waitingCostPerMinute;
}
public Double getRideCostPerMinute() {
return rideCostPerMinute;
}
public void setRideCostPerMinute(Double rideCostPerMinute) {
this.rideCostPerMinute = rideCostPerMinute;
}
public List<Object> getSurcharge() {
return surcharge;
}
public void setSurcharge(List<Object> surcharge) {
this.surcharge = surcharge;
}
public Boolean getRatesLowerThanUsual() {
return ratesLowerThanUsual;
}
public void setRatesLowerThanUsual(Boolean ratesLowerThanUsual) {
this.ratesLowerThanUsual = ratesLowerThanUsual;
}
public Boolean getRatesHigherThanUsual() {
return ratesHigherThanUsual;
}
public void setRatesHigherThanUsual(Boolean ratesHigherThanUsual) {
this.ratesHigherThanUsual = ratesHigherThanUsual;
}
}
-----------------------------------com.example.Message.java-----------------------------------
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Message {
#SerializedName("categories")
#Expose
private List<Category> categories = null;
#SerializedName("ride_estimate")
#Expose
private List<RideEstimate> rideEstimate = null;
public List<Category> getCategories() {
return categories;
}
public void setCategories(List<Category> categories) {
this.categories = categories;
}
public List<RideEstimate> getRideEstimate() {
return rideEstimate;
}
public void setRideEstimate(List<RideEstimate> rideEstimate) {
this.rideEstimate = rideEstimate;
}
}
-----------------------------------com.example.RideEstimate.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class RideEstimate {
#SerializedName("category")
#Expose
private String category;
#SerializedName("distance")
#Expose
private Double distance;
#SerializedName("travel_time_in_minutes")
#Expose
private Integer travelTimeInMinutes;
#SerializedName("amount_min")
#Expose
private Integer amountMin;
#SerializedName("amount_max")
#Expose
private Integer amountMax;
#SerializedName("discounts")
#Expose
private Discounts discounts;
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public Double getDistance() {
return distance;
}
public void setDistance(Double distance) {
this.distance = distance;
}
public Integer getTravelTimeInMinutes() {
return travelTimeInMinutes;
}
public void setTravelTimeInMinutes(Integer travelTimeInMinutes) {
this.travelTimeInMinutes = travelTimeInMinutes;
}
public Integer getAmountMin() {
return amountMin;
}
public void setAmountMin(Integer amountMin) {
this.amountMin = amountMin;
}
public Integer getAmountMax() {
return amountMax;
}
public void setAmountMax(Integer amountMax) {
this.amountMax = amountMax;
}
public Discounts getDiscounts() {
return discounts;
}
public void setDiscounts(Discounts discounts) {
this.discounts = discounts;
}
}
Now compile a library compile 'com.google.code.gson:gson:2.8.2'
then write few line to get your data fill in class
Gson gson = new Gson();
Example example = gson.fromJson(mainObj, Example.class);
Now you can try to fetch your categories like this
example.getCategories();

Categories

Resources