How to get JSON field using GSON and #SerializedName ? - android

I have an issue with parsing the following JSON object
"paymentCurrency": "eur",
"paymentOptions": [
{
"paymentOptionId": "1CeGuJt2nkxmaMVf",
"paymentProfileUpdateNeeded": false,
"status": "DISABLED",
"supportedCardTypes": [
"CARD_TYPE_1",
"CARD_TYPE_2",
"CARD_TYPE_3"
],
"type": "TYPE_1"
},
{
"paymentOptionId": "J8iAFXRZZC07rJdG",
"status": "DISABLED",
"type": "TYPE_2"
}
],
"tripCost": "3000",
This is what I've tried until now. I cannot use anything besides #SerializedName and GSON to parse the arrays. Please find the model class below :
public class MatchDetails {
//other fields
#SerializedName("paymentOptions")
public ArrayList<PaymentOptionWrapper> options;
}
public class PaymentOptionWrapper {
public PaymentOption option;
}
public class PaymentOption {
#SerializedName("paymentOptionId")
public String paymentOptionId;
#SerializedName("paymentProfileUpdateNeeded")
public boolean profileUpdateNeeded;
#SerializedName("status")
public String status;
#SerializedName("supportedCardTypes")
public ArrayList<String> supportedCards;
#SerializedName("type")
public String type;
}
I have also tried not using a wrapper, mapping the list directly but it is still null.

Try this...
public class MatchDetails {
//other fields
#SerializedName("paymentOptions")
public ArrayList<PaymentOption> options;
public ArrayList<PaymentOption> getOptions() {
return options;
}
public void setOptions(ArrayList<PaymentOption> options) {
this.options = options;
}
}
class PaymentOption {
#SerializedName("paymentOptionId")
public String paymentOptionId;
#SerializedName("paymentProfileUpdateNeeded")
public boolean profileUpdateNeeded;
#SerializedName("status")
public String status;
#SerializedName("supportedCardTypes")
public ArrayList<String> supportedCards;
#SerializedName("type")
public String type;
public String getPaymentOptionId() {
return paymentOptionId;
}
public void setPaymentOptionId(String paymentOptionId) {
this.paymentOptionId = paymentOptionId;
}
public boolean isProfileUpdateNeeded() {
return profileUpdateNeeded;
}
public void setProfileUpdateNeeded(boolean profileUpdateNeeded) {
this.profileUpdateNeeded = profileUpdateNeeded;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public ArrayList<String> getSupportedCards() {
return supportedCards;
}
public void setSupportedCards(ArrayList<String> supportedCards) {
this.supportedCards = supportedCards;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}

Try this:
public class MatchDetails implements Serializable
{
#SerializedName("paymentOptions")
#Expose
private List<PaymentOption> paymentOptions = null;
private final static long serialVersionUID = 7730239716376724487L;
public List<PaymentOption> getPaymentOptions() {
return paymentOptions;
}
public void setPaymentOptions(List<PaymentOption> paymentOptions) {
this.paymentOptions = paymentOptions;
}
}
and
public class PaymentOption implements Serializable
{
#SerializedName("paymentOptionId")
#Expose
private String paymentOptionId;
#SerializedName("paymentProfileUpdateNeeded")
#Expose
private Boolean paymentProfileUpdateNeeded;
#SerializedName("status")
#Expose
private String status;
#SerializedName("supportedCardTypes")
#Expose
private List<String> supportedCardTypes = null;
#SerializedName("type")
#Expose
private String type;
private final static long serialVersionUID = -5717104877176081166L;
public String getPaymentOptionId() {
return paymentOptionId;
}
public void setPaymentOptionId(String paymentOptionId) {
this.paymentOptionId = paymentOptionId;
}
public Boolean getPaymentProfileUpdateNeeded() {
return paymentProfileUpdateNeeded;
}
public void setPaymentProfileUpdateNeeded(Boolean paymentProfileUpdateNeeded) {
this.paymentProfileUpdateNeeded = paymentProfileUpdateNeeded;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public List<String> getSupportedCardTypes() {
return supportedCardTypes;
}
public void setSupportedCardTypes(List<String> supportedCardTypes) {
this.supportedCardTypes = supportedCardTypes;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}

Related

How to get JSON Array inside of a JSON Object and iterate

I am trying to communicate with an API using Retrofit in Android Studios but do not know how to get the JSON array within a JSON object.
JSON:
{
"result":{
"status":{
"msg":"success",
"code":200,
"action":2,
"execution_time":"0.505"
},
"page":"1",
"page_size":"40",
"q":"iphone",
"sort":"default",
"tmall":false,
"free_shiping":false,
"total_results":1924963,
"ip":"13.228.169.5",
"item":[
{
"num_iid":619354061232,
"pic":"https://img.alicdn.com/bao/uploaded/i4/2150908574/O1CN01O3Akm82DCwTChbTXg_!!2150908574.jpg",
"title":"Apple/苹果 iPhone XR iphone xs max手机双卡国行原装4G xr苹果x",
"price":"6000",
"promotion_price":"2009",
"sales":1973,
"loc":"广东 深圳",
"seller_id":2150908574,
"seller_nick":"实惠馆超市",
"shop_title":"新魔方数码",
"user_type":0,
"detail_url":"https://item.taobao.com/item.htm?id=619354061232",
"delivery_fee":"0.00"
}
"item":[...]
Method:
private void taobaoSearch(){
TaobaoInterface retrofitInterface = RetrofitInstance.getRetrofitInstanceTaobao().create(TaobaoInterface.class);
Call<TaobaoModel> listCall = retrofitInterface.getTaobao("item_search", "40","default", "iphone","taobao-api.p.rapidapi.com", "//apikey hidden");
listCall.enqueue(new Callback<TaobaoModel>() {
#Override
public void onResponse(Call<TaobaoModel> call, Response<TaobaoModel> response) {
//not sure what to do here
}
#Override
public void onFailure(Call<TaobaoModel> call, Throwable t) {
System.out.println("FAILED");
System.out.println(call);
t.printStackTrace();
}
});
}
TaobaoModel:
public class TaobaoModel {
#SerializedName("result")
private Result result;
public Result getResult() {
return result;
}
public void setResult(Result result) {
this.result = result;
}
}
Result:
public class Result {
#SerializedName("status")
private Status status;
#SerializedName("q")
private String q;
#SerializedName("page")
private String page;
#SerializedName("page_size")
private String page_size;
#SerializedName("total_results")
private int total_results;
#SerializedName("tmall")
private String tmall;
#SerializedName("sort")
private String sort;
#SerializedName("free_shiping")
private String free_shiping;
#SerializedName("ip")
private String ip;
#SerializedName("item")
private ArrayList<TaobaoItems> item;
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public String getQ() {
return q;
}
public void setQ(String q) {
this.q = q;
}
public String getPage() {
return page;
}
public void setPage(String page) {
this.page = page;
}
public String getPage_size() {
return page_size;
}
public void setPage_size(String page_size) {
this.page_size = page_size;
}
public int getTotal_results() {
return total_results;
}
public void setTotal_results(int total_results) {
this.total_results = total_results;
}
public String getTmall() {
return tmall;
}
public void setTmall(String tmall) {
this.tmall = tmall;
}
public String getSort() {
return sort;
}
public void setSort(String sort) {
this.sort = sort;
}
public String getFree_shiping() {
return free_shiping;
}
public void setFree_shiping(String free_shiping) {
this.free_shiping = free_shiping;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public ArrayList<TaobaoItems> getItem() {
return item;
}
public void setItem(ArrayList<TaobaoItems> item) {
this.item = item;
}
}
TaobaoItems
public class TaobaoItems {
#SerializedName("num_iid")
private long num_iid;
#SerializedName("pic")
private String pic;
#SerializedName("title")
private String title;
#SerializedName("price")
private String price;
#SerializedName("promotion_price")
private String promotion_price;
#SerializedName("sales")
private int sales;
#SerializedName("loc")
private String loc;
#SerializedName("seller_id")
private long seller_id;
#SerializedName("seller_nick")
private String seller_nick;
#SerializedName("shop_title")
private String shop_title;
#SerializedName("user_type")
private int user_type;
#SerializedName("detail_url")
private String detail_url;
#SerializedName("delivery_fee")
private String delivery_fee;
public TaobaoItems(String title, String price, String pic, String detail_url) {
this.pic = pic;
this.title = title;
this.price = price;
this.detail_url = detail_url;
}
public long getNum_iid() {
return num_iid;
}
public void setNum_iid(long num_iid) {
this.num_iid = num_iid;
}
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getPromotion_price() {
return promotion_price;
}
public void setPromotion_price(String promotion_price) {
this.promotion_price = promotion_price;
}
public int getSales() {
return sales;
}
public void setSales(int sales) {
this.sales = sales;
}
public String getLoc() {
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
public long getSeller_id() {
return seller_id;
}
public void setSeller_id(long seller_id) {
this.seller_id = seller_id;
}
public String getSeller_nick() {
return seller_nick;
}
public void setSeller_nick(String seller_nick) {
this.seller_nick = seller_nick;
}
public String getShop_title() {
return shop_title;
}
public void setShop_title(String shop_title) {
this.shop_title = shop_title;
}
public int getUser_type() {
return user_type;
}
public void setUser_type(int user_type) {
this.user_type = user_type;
}
public String getDetail_url() {
return detail_url;
}
public void setDetail_url(String detail_url) {
this.detail_url = detail_url;
}
public String getDelivery_fee() {
return delivery_fee;
}
public void setDelivery_fee(String delivery_fee) {
this.delivery_fee = delivery_fee;
}
}
Status:
public class Status {
#SerializedName("msg")
private String msg;
#SerializedName("code")
private int code;
#SerializedName("action")
private int action;
#SerializedName("execution_time")
private String execution_time;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public int getAction() {
return action;
}
public void setAction(int action) {
this.action = action;
}
public String getExecution_time() {
return execution_time;
}
public void setExecution_time(String execution_time) {
this.execution_time = execution_time;
}
}
My intention is to get the JSON Array item and display title,price,pic,detail_url from it. I found out how to display it one at a time so far, but couldn't find how to iterate the JSON object so that I can display the data in a listview. Please help, I am new to this and I've been stuck for quite awhile now. If you want to see my interface, retrofit instance etc just let me know.
private void taobaoSearch(){
TaobaoInterface retrofitInterface = RetrofitInstance.getRetrofitInstanceTaobao().create(TaobaoInterface.class);
Call<TaobaoModel> listCall = retrofitInterface.getTaobao("item_search", "40","default", "iphone","taobao-api.p.rapidapi.com", "//apikey hidden");
listCall.enqueue(new Callback<TaobaoModel>() {
#Override
public void onResponse(Call<TaobaoModel> call, Response<TaobaoModel> response) {
List<Result> retro=response.body().getitems();
generateDataList(retro);
}
#Override
public void onFailure(Call<TaobaoModel> call, Throwable t) {
System.out.println("FAILED");
System.out.println(call);
t.printStackTrace();
}
});
}
/*Method to generate List of data using RecyclerView with custom adapter*/
private void generateDataList(List<Result> dataList) {
recyclerView = findViewById(R.id.customRecycler);
adapter = new CustomAdapter(this,dataList);
recyclerView.setAdapter(adapter);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
}

Parse json response android retrofit

I am trying to parse response from server in Android studio.
But I am not getting all values in Arraylist.
I have created ItemData.java and ItemResponse.java
I am Calling Api using getItemData Method:
public void getItemData() {
Call<ItemDataResponse> call = service.getData(token, "200");
call.enqueue(new Callback<ItemDataResponse>() {
#Override
public void onResponse(#NonNull Call<ItemDataResponse> call, #NonNull Response<ItemDataResponse> response) {
Log.d("dataFromServer", response.body.toString());
}
#Override
public void onFailure(#NonNull Call<ItemDataResponse> call, #NonNull Throwable t) {
progressDoalog.dismiss();
Toast.makeText(LiveVehiclesActivity.this, "Something went wrong...Please try later!", Toast.LENGTH_SHORT).show();
}
});
}
This is Json response:
{
"code":"1",
"items":[
{
"item_id":"200",
"speed":"2"
},
{
"item_id":"201",
"speed":"0"
}
]
}
ItemsResponse.java:
public class ItemDataResponse implements Serializable {
#SerializedName("code")
private String code;
#SerializedName("items")
#Expose
private List<ItemData> items;
public String getResponsecode() {
return responsecode;
}
public void setResponsecode(String responsecode) {
this.responsecode = responsecode;
}
public List<ItemData> getItems() {
return items;
}
public void setItems(List<ItemData> items) {
this.items = items;
}
}
ItemData.java
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class ItemData {
#SerializedName("item_id")
#Expose
private String itemId;
#SerializedName("speed")
#Expose
private String speed;
public String getItemId() {
return itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
public String getSpeed() {
return speed;
}
public void setSpeed(String speed) {
this.speed = speed;
}
}
After run in debug mode I am getting response like:
code:"1"
items=null
your should modify
class ItemData {
private String item_id;
private String speed;
public String getItem_id() {
return item_id;
}
public void setItem_id(String item_id) {
this.item_id = item_id;
}
public String getSpeed() {
return speed;
}
public void setSpeed(String speed) {
this.speed = speed;
}
}
The ItemData model does not seem to be consistent with the JSON response.
i.e
{
"item_id":"200",
"speed":"2"
}
should map to:
class ItemData implements Serializable {
#SerializedName("item_id")
private String itemId;
#SerializedName("speed")
private String speed;
// getters and setters
}
Use SerializedName attribute for the field contains "_". Here for item_id in your ItemData class getting problem in mapping.
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class ItemData {
#SerializedName("item_id")
#Expose
private String itemId;
#SerializedName("speed")
#Expose
private String speed;
public String getItemId() {
return itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
public String getSpeed() {
return speed;
}
public void setSpeed(String speed) {
this.speed = speed;
}
}
please change your ItemDataResponse class also
public class ItemDataResponse {
#SerializedName("code")
#Expose
private String code;
#SerializedName("items")
#Expose
private List<Item> items = null;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
}

java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 2 column 1 error

I'm new to android programming. I have a class where retrofit API call is done to parse and display few attributes JSON file. But I get:
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING
at line 2 column 1
Kindly help. I searched for answers but I couldn't find anything wrong with the JSON response. Posted my JSON response and JAVA class:
JSON Response:
{
"status": 1,
"active_requests": [
{
"id": "12",
"driver_id": "2",
"booking_id": "12",
"request_status": "1",
"created_on": "2018-09-13 19:57:29",
"updated_on": "2018-09-13 19:57:29",
"customer_id": "1",
"pickup_location": "GN Mills",
"drop_location": "Vadavalli",
"pickup_latitude": "11.025625",
"pickup_longitude": "76.955467",
"drop_latitude": "18.5645654",
"drop_longitude": "17.5645654",
"pickup_date_time": "2018-09-28 15:25:00",
"drop_date_time": "2018-09-28 15:25:00",
"package_weight": "55.5",
"package_type": "1",
"package_description": "fdasd dsaD YDASYD",
"vechicle_type": "car",
"service_status": "1",
"total_distance": "0",
"service_fare": "3460.6110936131",
"driver_fare": "2768.4888748905",
"paid_amount": "0",
"card_id": "0",
"picked_time": "0000-00-00 00:00:00",
"dropped_time": "0000-00-00 00:00:00"
}
]
}
JAVA File:
public class DriverDashboardFragment extends Fragment {
View root_view;
#BindView(R.id.linear_detail)
LinearLayout linearDetail;
#BindView(R.id.img_back)
ImageView imgBack;
#BindView(R.id.txt_title)
TextView txt_title;
SharedPreferences sharedPreferences;
Unbinder unbinder;
Context context;
RecyclerView recyclerView;
DriverDashboardAdapter driverDashboardAdapter;
List<DriverRequestModel> driver_list;
String id;
public static DriverDashboardFragment newInstance() {
DriverDashboardFragment fragment = new DriverDashboardFragment();
return fragment;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
root_view = inflater.inflate(R.layout.driverfragment_dashboard, container, false);
unbinder = ButterKnife.bind(this, root_view);
context = getContext();
sharedPreferences = getActivity().getSharedPreferences("MyPref", 0); // 0 - for private mode
id = PrefConnect.readString(getActivity(), PrefConnect.CUSTOMER_ID, "");
String msg= sharedPreferences.getString("message","");
Log.i("TAG",msg);
txt_title.setText("Dashboard");
imgBack.setVisibility(View.GONE);
getActivity().getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
ApiService apiService = (ApiService) RetrofitSingleton.getApiService();
Call<DriverRequestModel> call = apiService.getdriverrequest();
call.enqueue(new Callback<DriverRequestModel>() {
#Override
public void onResponse(Call<DriverRequestModel> call, Response<DriverRequestModel> response) {
driver_list = new ArrayList<>();
DriverRequestModel promo=response.body();
driver_list = promo.getActiveRequests();
Log.e("Response = ",new Gson().toJson(response.body()));
PrefConnect.writeString(context,PrefConnect.CUSTOMER_ID,response.body().getCustomerId()+"");
recyclerView = (RecyclerView)root_view.findViewById(R.id.recyclerview);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
driverDashboardAdapter = new DriverDashboardAdapter(getContext(),driver_list);
recyclerView.setAdapter(driverDashboardAdapter);
}
#Override
public void onFailure(Call<DriverRequestModel> call, Throwable t) {
Log.e("TAG","Response = "+t.toString());
}
});
return root_view;
}
#OnClick({R.id.linear_detail})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.linear_detail:
Intent detail = new Intent(context, DriverServiceDetailActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("key_1", 1);
detail.putExtras(bundle);
startActivity(detail);
break;
}
}
}
Model Class:
public class DriverRequestModel {
#SerializedName("status")
#Expose
public Integer status;
#SerializedName("active_requests")
#Expose
public List<ActiveRequest> activeRequests = null;
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public List<ActiveRequest> getActiveRequests() {
return activeRequests;
}
public void setActiveRequests(List<ActiveRequest> activeRequests) {
this.activeRequests = activeRequests;
}
public class ActiveRequest {
#SerializedName("id")
#Expose
public String id;
#SerializedName("driver_id")
#Expose
public String driverId;
#SerializedName("booking_id")
#Expose
public String bookingId;
#SerializedName("request_status")
#Expose
public String requestStatus;
#SerializedName("created_on")
#Expose
public String createdOn;
#SerializedName("updated_on")
#Expose
public String updatedOn;
#SerializedName("customer_id")
#Expose
public String customerId;
#SerializedName("pickup_location")
#Expose
public String pickupLocation;
#SerializedName("drop_location")
#Expose
public String dropLocation;
#SerializedName("pickup_latitude")
#Expose
public String pickupLatitude;
#SerializedName("pickup_longitude")
#Expose
public String pickupLongitude;
#SerializedName("drop_latitude")
#Expose
public String dropLatitude;
#SerializedName("drop_longitude")
#Expose
public String dropLongitude;
#SerializedName("pickup_date_time")
#Expose
public String pickupDateTime;
#SerializedName("drop_date_time")
#Expose
public String dropDateTime;
#SerializedName("package_weight")
#Expose
public String packageWeight;
#SerializedName("package_type")
#Expose
public String packageType;
#SerializedName("package_description")
#Expose
public String packageDescription;
#SerializedName("vechicle_type")
#Expose
public String vechicleType;
#SerializedName("service_status")
#Expose
public String serviceStatus;
#SerializedName("total_distance")
#Expose
public String totalDistance;
#SerializedName("service_fare")
#Expose
public String serviceFare;
#SerializedName("driver_fare")
#Expose
public String driverFare;
#SerializedName("paid_amount")
#Expose
public String paidAmount;
#SerializedName("card_id")
#Expose
public String cardId;
#SerializedName("picked_time")
#Expose
public String pickedTime;
#SerializedName("dropped_time")
#Expose
public String droppedTime;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDriverId() {
return driverId;
}
public void setDriverId(String driverId) {
this.driverId = driverId;
}
public String getBookingId() {
return bookingId;
}
public void setBookingId(String bookingId) {
this.bookingId = bookingId;
}
public String getRequestStatus() {
return requestStatus;
}
public void setRequestStatus(String requestStatus) {
this.requestStatus = requestStatus;
}
public String getCreatedOn() {
return createdOn;
}
public void setCreatedOn(String createdOn) {
this.createdOn = createdOn;
}
public String getUpdatedOn() {
return updatedOn;
}
public void setUpdatedOn(String updatedOn) {
this.updatedOn = updatedOn;
}
public String getCustomerId() {
return customerId;
}
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
public String getPickupLocation() {
return pickupLocation;
}
public void setPickupLocation(String pickupLocation) {
this.pickupLocation = pickupLocation;
}
public String getDropLocation() {
return dropLocation;
}
public void setDropLocation(String dropLocation) {
this.dropLocation = dropLocation;
}
public String getPickupLatitude() {
return pickupLatitude;
}
public void setPickupLatitude(String pickupLatitude) {
this.pickupLatitude = pickupLatitude;
}
public String getPickupLongitude() {
return pickupLongitude;
}
public void setPickupLongitude(String pickupLongitude) {
this.pickupLongitude = pickupLongitude;
}
public String getDropLatitude() {
return dropLatitude;
}
public void setDropLatitude(String dropLatitude) {
this.dropLatitude = dropLatitude;
}
public String getDropLongitude() {
return dropLongitude;
}
public void setDropLongitude(String dropLongitude) {
this.dropLongitude = dropLongitude;
}
public String getPickupDateTime() {
return pickupDateTime;
}
public void setPickupDateTime(String pickupDateTime) {
this.pickupDateTime = pickupDateTime;
}
public String getDropDateTime() {
return dropDateTime;
}
public void setDropDateTime(String dropDateTime) {
this.dropDateTime = dropDateTime;
}
public String getPackageWeight() {
return packageWeight;
}
public void setPackageWeight(String packageWeight) {
this.packageWeight = packageWeight;
}
public String getPackageType() {
return packageType;
}
public void setPackageType(String packageType) {
this.packageType = packageType;
}
public String getPackageDescription() {
return packageDescription;
}
public void setPackageDescription(String packageDescription) {
this.packageDescription = packageDescription;
}
public String getVechicleType() {
return vechicleType;
}
public void setVechicleType(String vechicleType) {
this.vechicleType = vechicleType;
}
public String getServiceStatus() {
return serviceStatus;
}
public void setServiceStatus(String serviceStatus) {
this.serviceStatus = serviceStatus;
}
public String getTotalDistance() {
return totalDistance;
}
public void setTotalDistance(String totalDistance) {
this.totalDistance = totalDistance;
}
public String getServiceFare() {
return serviceFare;
}
public void setServiceFare(String serviceFare) {
this.serviceFare = serviceFare;
}
public String getDriverFare() {
return driverFare;
}
public void setDriverFare(String driverFare) {
this.driverFare = driverFare;
}
public String getPaidAmount() {
return paidAmount;
}
public void setPaidAmount(String paidAmount) {
this.paidAmount = paidAmount;
}
public String getCardId() {
return cardId;
}
public void setCardId(String cardId) {
this.cardId = cardId;
}
public String getPickedTime() {
return pickedTime;
}
public void setPickedTime(String pickedTime) {
this.pickedTime = pickedTime;
}
public String getDroppedTime() {
return droppedTime;
}
public void setDroppedTime(String droppedTime) {
this.droppedTime = droppedTime;
}
}
}
Are you using the right model for mapping your response? Should it be:
DriverRequestModel driverRequestModel = response.body();

Fetching json object from JSON string

I am new to Android and I am developing app which has server side functionality. I am getting response in JSON format.
My response is shown as this image.
I know how to parse json using Volley but I don't know hot to parse using GSON. Previous code of my app was written by some one else. Now I have to complete this code. but I do not know how he getting data from JSON string.
I need JSON arrays in different activity. Array response:
image
Here is some snaps of my code.
Code for adapter for activity one
topicListAdapter = new TopicListAdapter(TopicActivity.this,
myCourseListMain. getCourseArrayList().get(Integer.parseInt(course_position)).
getTopicListMain().getTopicDetailsArrayList(), flag);
listAlltopics.setAdapter(topicListAdapter);
in which I got list of topics
here is code for second activity list adapter
lessionListAdapter = new LessionListAdapter(LessionActivity.this,
myCourseListMain. getCourseArrayList(). get(Integer.parseInt(course_position)).
getTopicListMain().getTopicDetailsArrayList().get(Integer.parseInt(topic_position)).getLessionArrayList(), flag);
by this code i got array of lession in second activity
Now I want sublession array in third activity but I don't know how to get it.
Here is what I tried
lessionListAdapter = new DummyAdapter(DummyTopicList.this,
myCourseListMain . getCourseArrayList(). get(Integer.parseInt(course_position)).
getTopicListMain() . getTopicDetailsArrayList() .get(Integer.parseInt(topic_position)).
getLessionLIstMain() .getLessionLIstDetailArrayList().get(Integer.parseInt(lession_position)). , flag);
listAlllessions.setAdapter(lessionListAdapter);
Here are some other classes which helpful to you for understand
public class MyCourseListMain {
#SerializedName("data")
private ArrayList<Course> courseArrayList;
public ArrayList<Course> getCourseArrayList() {
return courseArrayList;
}
public void setCourseArrayList(ArrayList<Course> courseArrayList) {
this.courseArrayList = courseArrayList;
}
}
class for course
public class Course {
#SerializedName("img")
private String img;
#SerializedName("title")
private String title;
#SerializedName("institute_id")
private String institute_id;
#SerializedName("institute_name")
private String institute_name;
#SerializedName("expired")
private String expired;
#SerializedName("status")
private String status;
#SerializedName("subscribe_box")
private String subscribe_box;
#SerializedName("expire_on")
private String expire_on;
#SerializedName("item_id")
private String item_id;
#SerializedName("rated")
private String rated;
private TopicListMain topicListMain;
public String getRated() {
return rated;
}
public void setRated(String rated) {
this.rated = rated;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getInstitute_id() {
return institute_id;
}
public void setInstitute_id(String institute_id) {
this.institute_id = institute_id;
}
public String getInstitute_name() {
return institute_name;
}
public void setInstitute_name(String institute_name) {
this.institute_name = institute_name;
}
public String getExpired() {
return expired;
}
public void setExpired(String expired) {
this.expired = expired;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getSubscribe_box() {
return subscribe_box;
}
public void setSubscribe_box(String subscribe_box) {
this.subscribe_box = subscribe_box;
}
public String getExpire_on() {
return expire_on;
}
public void setExpire_on(String expire_on) {
this.expire_on = expire_on;
}
public String getItem_id() {
return item_id;
}
public void setItem_id(String item_id) {
this.item_id = item_id;
}
public TopicListMain getTopicListMain() {
return topicListMain;
}
public void setTopicListMain(TopicListMain topicListMain) {
this.topicListMain = topicListMain; } }
class for topiclist_main
public class TopicListMain {
#SerializedName("data")
private ArrayList<TopicDetails> topicDetailsArrayList;
public ArrayList<TopicDetails> getTopicDetailsArrayList() {
return topicDetailsArrayList;
}
public void setTopicDetailsArrayList(ArrayList<TopicDetails> topicDetailsArrayList) {
this.topicDetailsArrayList = topicDetailsArrayList; }}
class for topic details
public class TopicDetails
{
#SerializedName("topic_id")
private String topic_id;
#SerializedName("title")
private String title;
#SerializedName("locked")
private String locked;
#SerializedName("lessons")
private ArrayList<Lession> lessionArrayList;
private LessionLIstMain lessionLIstMain;
public LessionLIstMain getLessionLIstMain() {
return lessionLIstMain;
}
public void setLessionLIstMain(LessionLIstMain lessionLIstMain) {
this.lessionLIstMain = lessionLIstMain;
}
public String getTopic_id() {
return topic_id;
}
public void setTopic_id(String topic_id) {
this.topic_id = topic_id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLocked() {
return locked;
}
public void setLocked(String locked) {
this.locked = locked;
}
public ArrayList<Lession> getLessionArrayList() {
return lessionArrayList;
}
public void setLessionArrayList(ArrayList<Lession> lessionArrayList) {
this.lessionArrayList = lessionArrayList; }}
https://github.com/google/gson
Make your object have same construct with your data which you got.And
YourObject val = new Gson().fromJson(new String(YourString.getBytes("ISO-8859-1"),
"UTF-8"), YourObject.class);
finally i got my solution by below code.
lessionListAdapter = new DummyAdapter(DummyTopicList.this,
myCourseListMain . getCourseArrayList(). get(Integer.parseInt(course_position)).
getTopicListMain() . getTopicDetailsArrayList() .get(Integer.parseInt(topic_position)).
getLessionArrayList().get(Integer.parseInt((lession_position))).getLessionLIstDetailArrayList() , flag);
listAlllessions.setAdapter(lessionListAdapter);
i also made some few classes to handle json array.
public class SubLessionDetail {
#SerializedName("lesson_id")
private String lession_id;
#SerializedName("title")
private String title;
#SerializedName("locked")
private String locked;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLocked() {
return locked;
}
public void setLocked(String locked) {
this.locked = locked;
}
public String getLession_id() {
return lession_id;
}
public void setLession_id(String lession_id) {
this.lession_id = lession_id;
}
}

Default Constructor issue while using Jackson Parser

My model getter setter class looks like this:-
#JsonIgnoreProperties(ignoreUnknown = true)
public class CuratedOffers {
public CuratedOffers() {
}
#JsonProperty("response")
private String response;
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
#JsonProperty("data")
private Data mData;
public Data getmData() {
return mData;
}
public void setmData(Data mData) {
this.mData = mData;
}
#JsonIgnoreProperties(ignoreUnknown = true)
public class Data{
#JsonProperty("vendors")
private List<Vendor> vendorList;
public List<Vendor> getVendorList() {
return vendorList;
}
public void setVendorList(List<Vendor> vendorList) {
this.vendorList = vendorList;
}
}
#JsonIgnoreProperties(ignoreUnknown = true)
public static class Vendor {
#JsonProperty("id")
private String Id;
public String getId() {
return Id;
}
public void setId(String id) {
Id = id;
}
#JsonProperty("name")
private String venName;
public String getVenName() {
return venName;
}
public void setVenName(String venName) {
this.venName = venName;
}
#JsonProperty("image")
private String image;
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
#JsonProperty("logo")
private String logo;
public String getLogo() {
return logo;
}
public void setLogo(String logo) {
this.logo = logo;
}
#JsonProperty("offers")
private String offers;
public String getOffers() {
return offers;
}
public void setOffers(String offers) {
this.offers = offers;
}
#JsonProperty("description")
private String offer_description;
public void setOffer_description(String offer_description) {
this.offer_description = offer_description;
}
public String getOffer_description() {
return offer_description;
}
}
}
And i using Jackson while compiling through gradle ie:-
compile 'com.fasterxml.jackson.core:jackson-databind:2.4.2'
compile 'com.fasterxml.jackson.core:jackson-annotations:2.4.2'
compile 'com.fasterxml.jackson.core:jackson-core:2.4.2'
After compiling i keep getting this error in my stacktrace
com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class com.yoy.CuratedOffers$Data]: can not instantiate from JSON object (need to add/enable type information?)
Searched SO without any suitable answers.Help would be appreciated!!
As suggested by #vilpel89 i had forgot to declare a static nested class inside CuratedOffers class.Now my updated class is:-
#JsonIgnoreProperties(ignoreUnknown = true)
public class CuratedOffers {
public CuratedOffers() {
}
#JsonProperty("response")
private String response;
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
#JsonProperty("data")
private Data mData;
public Data getmData() {
return mData;
}
public void setmData(Data mData) {
this.mData = mData;
}
#JsonIgnoreProperties(ignoreUnknown = true)
public static class Data{
public Data() {
}
#JsonProperty("vendors")
private List<Vendor> vendorList;
public List<Vendor> getVendorList() {
return vendorList;
}
public void setVendorList(List<Vendor> vendorList) {
this.vendorList = vendorList;
}
}
#JsonIgnoreProperties(ignoreUnknown = true)
public static class Vendor {
public Vendor() {
}
#JsonProperty("id")
private String Id;
public String getId() {
return Id;
}
public void setId(String id) {
Id = id;
}
#JsonProperty("name")
private String venName;
public String getVenName() {
return venName;
}
public void setVenName(String venName) {
this.venName = venName;
}
#JsonProperty("image")
private String image;
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
#JsonProperty("logo")
private String logo;
public String getLogo() {
return logo;
}
public void setLogo(String logo) {
this.logo = logo;
}
#JsonProperty("offers")
private String offers;
public String getOffers() {
return offers;
}
public void setOffers(String offers) {
this.offers = offers;
}
#JsonProperty("description")
private String offer_description;
public void setOffer_description(String offer_description) {
this.offer_description = offer_description;
}
public String getOffer_description() {
return offer_description;
}
}
}
Added a static constructor to my Data class as well as Vendor Class and also added default constructors to it.Now it's working like a charm!Hope it might help someone someday!

Categories

Resources