Android Java expected begin_object but was begin_array - java

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

As you can see in JSON response, errors and parameters are comes as List.
So please change fields to list in Covid19Model
#SerializedName("parameters")
#Expose
private List<Parameters> parameters;
#SerializedName("errors")
#Expose
private List<Errors> errors;

Related

Only one HTTP method is allowed. Found GET and PUT

java.lang.IllegalArgumentException: Only one HTTP method is allowed. Found: GET and PUT.
for method ApiInterface.UpdateCoordinates
i have tried for the last 2 hours to update the coordinates but it ain't working keeps throwing this error
java.lang.IllegalArgumentException: Only one HTTP method is allowed. Found: GET and PUT.
for method ApiInterface.UpdateCoordinates
at retrofit2.Utils.methodError(Utils.java:52)
at retrofit2.Utils.methodError(Utils.java:42)
at retrofit2.RequestFactory$Builder.parseHttpMethodAndPath(RequestFactory.java:251)
at retrofit2.RequestFactory$Builder.parseMethodAnnotation(RequestFactory.java:224)
at retrofit2.RequestFactory$Builder.build(RequestFactory.java:171)
at retrofit2.RequestFactory.parseAnnotations(RequestFactory.java:67)
at retrofit2.ServiceMethod.parseAnnotations(ServiceMethod.java:26)
at retrofit2.Retrofit.loadServiceMethod(Retrofit.java:170)
at retrofit2.Retrofit$1.invoke(Retrofit.java:149)
at java.lang.reflect.Proxy.invoke(Proxy.java:1006)
at $Proxy0.UpdateCoordinates(Unknown Source)
at com.example.charlo.jkuat_mobile_app.util.LocationService$1.onLocationResult(LocationService.java:54)
Model classes
the update model class
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class GpsUpdate {
#SerializedName("success")
#Expose
private Boolean success;
#SerializedName("data")
#Expose
private Data data;
#SerializedName("message")
#Expose
private String message;
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
model class
the data model class
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Data {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("driverid")
#Expose
private Integer driverid;
#SerializedName("companyid")
#Expose
private Integer companyid;
#SerializedName("vehicleid")
#Expose
private Integer vehicleid;
#SerializedName("warehouseid")
#Expose
private Integer warehouseid;
#SerializedName("orders")
#Expose
private Integer orders;
#SerializedName("status")
#Expose
private Integer status;
#SerializedName("latitute")
#Expose
private String latitute;
#SerializedName("longitude")
#Expose
private String longitude;
#SerializedName("tripdate")
#Expose
private String tripdate;
#SerializedName("created_at")
#Expose
private String createdAt;
#SerializedName("updated_at")
#Expose
private String updatedAt;
public Data(String latitute, String longitude) {
this.latitute = latitute;
this.longitude = longitude;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getDriverid() {
return driverid;
}
public void setDriverid(Integer driverid) {
this.driverid = driverid;
}
public Integer getCompanyid() {
return companyid;
}
public void setCompanyid(Integer companyid) {
this.companyid = companyid;
}
public Integer getVehicleid() {
return vehicleid;
}
public void setVehicleid(Integer vehicleid) {
this.vehicleid = vehicleid;
}
public Integer getWarehouseid() {
return warehouseid;
}
public void setWarehouseid(Integer warehouseid) {
this.warehouseid = warehouseid;
}
public Integer getOrders() {
return orders;
}
public void setOrders(Integer orders) {
this.orders = orders;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getLatitute() {
return latitute;
}
public void setLatitute(String latitute) {
this.latitute = latitute;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getTripdate() {
return tripdate;
}
public void setTripdate(String tripdate) {
this.tripdate = tripdate;
}
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;
}
}
Interface
interface class
#PUT("update_driver/{dispatchid}?")
Call<GpsUpdate> UpdateCoordinates(#Path("dispatchid") int id, #Field("latitude") String latitude, #Field("longitude") String longitude );
location service class
the update class which sends the coordinates to the backend
#Override
public void onCreate() {
super.onCreate();
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
tokenManager = TokenManager.getInstance(getSharedPreferences("prefs", MODE_PRIVATE));
service = ApiClient.createService(ApiInterface.class);
locationCallback = new LocationCallback(){
#Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
double lat = locationResult.getLastLocation().getLatitude();
double lng = locationResult.getLastLocation().getLongitude();
String latitude = String.valueOf(lat);
String longitude = String.valueOf(lng);
Data data = new Data(latitude,longitude);
Call<GpsUpdate> call = service.UpdateCoordinates(tokenManager.getToken().getDispatchid(),data.getLatitute(), data.getLongitude());
call.enqueue(new Callback<GpsUpdate>() {
#Override
public void onResponse(Call<GpsUpdate> call, Response<GpsUpdate> response) {
}
#Override
public void onFailure(Call<GpsUpdate> call, Throwable t) {
}
});
I think I should have marked this as a duplicate:
Retrofit: how fix "only one http method is allowed. found: get and get"?
Try changing the
#Path("dispatchid") int id
to
#Path("dispatchid") int dispatchid

Using GSON to parse an JSON object with an array of elements

How can I use GSON to parse the following JSON object:
{
"ProductsByCategory": [
{.....},
{.....},
{.....},
{.....},
]
}
The JSON object contains an array of elements. I am using GSON to try and parse the JSON and have the following POJO classes to assist me with this.
public class ProductItems {
#SerializedName("ProductsByCategory")
#Expose
private List<ProductsByCategory> productsByCategory = null;
public List<ProductsByCategory> getProductsByCategory() {
return productsByCategory;
}
public void setProductsByCategory(List<ProductsByCategory> productsByCategory) {
this.productsByCategory = productsByCategory;
}
}
public class ProductsByCategory {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("slug")
#Expose
private String slug;
#SerializedName("permalink")
#Expose
private String permalink;
#SerializedName("date_created")
#Expose
private String dateCreated;
#SerializedName("date_created_gmt")
#Expose
private String dateCreatedGmt;
#SerializedName("date_modified")
#Expose
private String dateModified;
#SerializedName("date_modified_gmt")
#Expose
private String dateModifiedGmt;
#SerializedName("type")
#Expose
private String type;
#SerializedName("status")
#Expose
private String status;
#SerializedName("featured")
#Expose
private Boolean featured;
#SerializedName("catalog_visibility")
#Expose
private String catalogVisibility;
#SerializedName("description")
#Expose
private String description;
#SerializedName("short_description")
#Expose
private String shortDescription;
#SerializedName("sku")
#Expose
private String sku;
#SerializedName("price")
#Expose
private String price;
#SerializedName("regular_price")
#Expose
private String regularPrice;
#SerializedName("sale_price")
#Expose
private String salePrice;
#SerializedName("date_on_sale_from")
#Expose
private Object dateOnSaleFrom;
#SerializedName("date_on_sale_from_gmt")
#Expose
private Object dateOnSaleFromGmt;
#SerializedName("date_on_sale_to")
#Expose
private Object dateOnSaleTo;
#SerializedName("date_on_sale_to_gmt")
#Expose
private Object dateOnSaleToGmt;
#SerializedName("price_html")
#Expose
private String priceHtml;
#SerializedName("on_sale")
#Expose
private Boolean onSale;
#SerializedName("purchasable")
#Expose
private Boolean purchasable;
#SerializedName("total_sales")
#Expose
private Integer totalSales;
#SerializedName("virtual")
#Expose
private Boolean virtual;
#SerializedName("downloadable")
#Expose
private Boolean downloadable;
#SerializedName("downloads")
#Expose
private List<Object> downloads = null;
#SerializedName("download_limit")
#Expose
private Integer downloadLimit;
#SerializedName("download_expiry")
#Expose
private Integer downloadExpiry;
#SerializedName("external_url")
#Expose
private String externalUrl;
#SerializedName("button_text")
#Expose
private String buttonText;
#SerializedName("tax_status")
#Expose
private String taxStatus;
#SerializedName("tax_class")
#Expose
private String taxClass;
#SerializedName("manage_stock")
#Expose
private Boolean manageStock;
#SerializedName("stock_quantity")
#Expose
private Integer stockQuantity;
#SerializedName("in_stock")
#Expose
private Boolean inStock;
#SerializedName("backorders")
#Expose
private String backorders;
#SerializedName("backorders_allowed")
#Expose
private Boolean backordersAllowed;
#SerializedName("backordered")
#Expose
private Boolean backordered;
#SerializedName("sold_individually")
#Expose
private Boolean soldIndividually;
#SerializedName("weight")
#Expose
private String weight;
#SerializedName("dimensions")
#Expose
private Dimensions dimensions;
#SerializedName("shipping_required")
#Expose
private Boolean shippingRequired;
#SerializedName("shipping_taxable")
#Expose
private Boolean shippingTaxable;
#SerializedName("shipping_class")
#Expose
private String shippingClass;
#SerializedName("shipping_class_id")
#Expose
private Integer shippingClassId;
#SerializedName("reviews_allowed")
#Expose
private Boolean reviewsAllowed;
#SerializedName("average_rating")
#Expose
private String averageRating;
#SerializedName("rating_count")
#Expose
private Integer ratingCount;
#SerializedName("related_ids")
#Expose
private List<Integer> relatedIds = null;
#SerializedName("upsell_ids")
#Expose
private List<Object> upsellIds = null;
#SerializedName("cross_sell_ids")
#Expose
private List<Object> crossSellIds = null;
#SerializedName("parent_id")
#Expose
private Integer parentId;
#SerializedName("purchase_note")
#Expose
private String purchaseNote;
#SerializedName("categories")
#Expose
private List<Category> categories = null;
#SerializedName("tags")
#Expose
private List<Object> tags = null;
#SerializedName("images")
#Expose
private List<Image> images = null;
#SerializedName("attributes")
#Expose
private List<Attribute> attributes = null;
#SerializedName("default_attributes")
#Expose
private List<Object> defaultAttributes = null;
#SerializedName("variations")
#Expose
private List<Integer> variations = null;
#SerializedName("grouped_products")
#Expose
private List<Object> groupedProducts = null;
#SerializedName("menu_order")
#Expose
private Integer menuOrder;
#SerializedName("meta_data")
#Expose
private List<MetaDatum> metaData = null;
#SerializedName("_links")
#Expose
private Links links;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public String getPermalink() {
return permalink;
}
public void setPermalink(String permalink) {
this.permalink = permalink;
}
public String getDateCreated() {
return dateCreated;
}
public void setDateCreated(String dateCreated) {
this.dateCreated = dateCreated;
}
public String getDateCreatedGmt() {
return dateCreatedGmt;
}
public void setDateCreatedGmt(String dateCreatedGmt) {
this.dateCreatedGmt = dateCreatedGmt;
}
public String getDateModified() {
return dateModified;
}
public void setDateModified(String dateModified) {
this.dateModified = dateModified;
}
public String getDateModifiedGmt() {
return dateModifiedGmt;
}
public void setDateModifiedGmt(String dateModifiedGmt) {
this.dateModifiedGmt = dateModifiedGmt;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Boolean getFeatured() {
return featured;
}
public void setFeatured(Boolean featured) {
this.featured = featured;
}
public String getCatalogVisibility() {
return catalogVisibility;
}
public void setCatalogVisibility(String catalogVisibility) {
this.catalogVisibility = catalogVisibility;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getShortDescription() {
return shortDescription;
}
public void setShortDescription(String shortDescription) {
this.shortDescription = shortDescription;
}
public String getSku() {
return sku;
}
public void setSku(String sku) {
this.sku = sku;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getRegularPrice() {
return regularPrice;
}
public void setRegularPrice(String regularPrice) {
this.regularPrice = regularPrice;
}
public String getSalePrice() {
return salePrice;
}
public void setSalePrice(String salePrice) {
this.salePrice = salePrice;
}
public Object getDateOnSaleFrom() {
return dateOnSaleFrom;
}
public void setDateOnSaleFrom(Object dateOnSaleFrom) {
this.dateOnSaleFrom = dateOnSaleFrom;
}
public Object getDateOnSaleFromGmt() {
return dateOnSaleFromGmt;
}
public void setDateOnSaleFromGmt(Object dateOnSaleFromGmt) {
this.dateOnSaleFromGmt = dateOnSaleFromGmt;
}
public Object getDateOnSaleTo() {
return dateOnSaleTo;
}
public void setDateOnSaleTo(Object dateOnSaleTo) {
this.dateOnSaleTo = dateOnSaleTo;
}
public Object getDateOnSaleToGmt() {
return dateOnSaleToGmt;
}
public void setDateOnSaleToGmt(Object dateOnSaleToGmt) {
this.dateOnSaleToGmt = dateOnSaleToGmt;
}
public String getPriceHtml() {
return priceHtml;
}
public void setPriceHtml(String priceHtml) {
this.priceHtml = priceHtml;
}
public Boolean getOnSale() {
return onSale;
}
public void setOnSale(Boolean onSale) {
this.onSale = onSale;
}
public Boolean getPurchasable() {
return purchasable;
}
public void setPurchasable(Boolean purchasable) {
this.purchasable = purchasable;
}
public Integer getTotalSales() {
return totalSales;
}
public void setTotalSales(Integer totalSales) {
this.totalSales = totalSales;
}
public Boolean getVirtual() {
return virtual;
}
public void setVirtual(Boolean virtual) {
this.virtual = virtual;
}
public Boolean getDownloadable() {
return downloadable;
}
public void setDownloadable(Boolean downloadable) {
this.downloadable = downloadable;
}
public List<Object> getDownloads() {
return downloads;
}
public void setDownloads(List<Object> downloads) {
this.downloads = downloads;
}
public Integer getDownloadLimit() {
return downloadLimit;
}
public void setDownloadLimit(Integer downloadLimit) {
this.downloadLimit = downloadLimit;
}
public Integer getDownloadExpiry() {
return downloadExpiry;
}
public void setDownloadExpiry(Integer downloadExpiry) {
this.downloadExpiry = downloadExpiry;
}
public String getExternalUrl() {
return externalUrl;
}
public void setExternalUrl(String externalUrl) {
this.externalUrl = externalUrl;
}
public String getButtonText() {
return buttonText;
}
public void setButtonText(String buttonText) {
this.buttonText = buttonText;
}
public String getTaxStatus() {
return taxStatus;
}
public void setTaxStatus(String taxStatus) {
this.taxStatus = taxStatus;
}
public String getTaxClass() {
return taxClass;
}
public void setTaxClass(String taxClass) {
this.taxClass = taxClass;
}
public Boolean getManageStock() {
return manageStock;
}
public void setManageStock(Boolean manageStock) {
this.manageStock = manageStock;
}
public Integer getStockQuantity() {
return stockQuantity;
}
public void setStockQuantity(Integer stockQuantity) {
this.stockQuantity = stockQuantity;
}
public Boolean getInStock() {
return inStock;
}
public void setInStock(Boolean inStock) {
this.inStock = inStock;
}
public String getBackorders() {
return backorders;
}
public void setBackorders(String backorders) {
this.backorders = backorders;
}
public Boolean getBackordersAllowed() {
return backordersAllowed;
}
public void setBackordersAllowed(Boolean backordersAllowed) {
this.backordersAllowed = backordersAllowed;
}
public Boolean getBackordered() {
return backordered;
}
public void setBackordered(Boolean backordered) {
this.backordered = backordered;
}
public Boolean getSoldIndividually() {
return soldIndividually;
}
public void setSoldIndividually(Boolean soldIndividually) {
this.soldIndividually = soldIndividually;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public Dimensions getDimensions() {
return dimensions;
}
public void setDimensions(Dimensions dimensions) {
this.dimensions = dimensions;
}
public Boolean getShippingRequired() {
return shippingRequired;
}
public void setShippingRequired(Boolean shippingRequired) {
this.shippingRequired = shippingRequired;
}
public Boolean getShippingTaxable() {
return shippingTaxable;
}
public void setShippingTaxable(Boolean shippingTaxable) {
this.shippingTaxable = shippingTaxable;
}
public String getShippingClass() {
return shippingClass;
}
public void setShippingClass(String shippingClass) {
this.shippingClass = shippingClass;
}
public Integer getShippingClassId() {
return shippingClassId;
}
public void setShippingClassId(Integer shippingClassId) {
this.shippingClassId = shippingClassId;
}
public Boolean getReviewsAllowed() {
return reviewsAllowed;
}
public void setReviewsAllowed(Boolean reviewsAllowed) {
this.reviewsAllowed = reviewsAllowed;
}
public String getAverageRating() {
return averageRating;
}
public void setAverageRating(String averageRating) {
this.averageRating = averageRating;
}
public Integer getRatingCount() {
return ratingCount;
}
public void setRatingCount(Integer ratingCount) {
this.ratingCount = ratingCount;
}
public List<Integer> getRelatedIds() {
return relatedIds;
}
public void setRelatedIds(List<Integer> relatedIds) {
this.relatedIds = relatedIds;
}
public List<Object> getUpsellIds() {
return upsellIds;
}
public void setUpsellIds(List<Object> upsellIds) {
this.upsellIds = upsellIds;
}
public List<Object> getCrossSellIds() {
return crossSellIds;
}
public void setCrossSellIds(List<Object> crossSellIds) {
this.crossSellIds = crossSellIds;
}
public Integer getParentId() {
return parentId;
}
public void setParentId(Integer parentId) {
this.parentId = parentId;
}
public String getPurchaseNote() {
return purchaseNote;
}
public void setPurchaseNote(String purchaseNote) {
this.purchaseNote = purchaseNote;
}
public List<Category> getCategories() {
return categories;
}
public void setCategories(List<Category> categories) {
this.categories = categories;
}
public List<Object> getTags() {
return tags;
}
public void setTags(List<Object> tags) {
this.tags = tags;
}
public List<Image> getImages() {
return images;
}
public void setImages(List<Image> images) {
this.images = images;
}
public List<Attribute> getAttributes() {
return attributes;
}
public void setAttributes(List<Attribute> attributes) {
this.attributes = attributes;
}
public List<Object> getDefaultAttributes() {
return defaultAttributes;
}
public void setDefaultAttributes(List<Object> defaultAttributes) {
this.defaultAttributes = defaultAttributes;
}
public List<Integer> getVariations() {
return variations;
}
public void setVariations(List<Integer> variations) {
this.variations = variations;
}
public List<Object> getGroupedProducts() {
return groupedProducts;
}
public void setGroupedProducts(List<Object> groupedProducts) {
this.groupedProducts = groupedProducts;
}
public Integer getMenuOrder() {
return menuOrder;
}
public void setMenuOrder(Integer menuOrder) {
this.menuOrder = menuOrder;
}
public List<MetaDatum> getMetaData() {
return metaData;
}
public void setMetaData(List<MetaDatum> metaData) {
this.metaData = metaData;
}
public Links getLinks() {
return links;
}
public void setLinks(Links links) {
this.links = links;
}
}
The code that I use is the following:
public void onResponse(Call call, Response response) throws IOException
{
String mMessage = response.body().string();
if (response.isSuccessful())
{
try
{
Gson gson = new Gson();
final ProductItems categoryProducts = gson.fromJson(mMessage, ProductItems.class);
response.close();
}
catch (Exception e)
{
Log.e("Error", "Failed to upload");
e.printStackTrace();
}
However, I get the following error: GSON throwing “Expected BEGIN_OBJECT but was BEGIN_ARRAY.
I have tried to change the ProductItems class to taking an object for productbycategories but then I get the following error: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 2324 path $.ProductsByCategory[0].meta_data[0].value. I am now a bit confused.
The reason you get this error is that the data is not consistent with the way the POJO is generated.
This is the specific part of the data that has the issue:
"meta_data": [
{
"id": 14232,
"key": "_vc_post_settings",
"value": {
"vc_grid_id": []
}
},
{
"id": 14273,
"key": "fb_product_description",
"value": ""
},
{
"id": 14274,
"key": "fb_visibility",
"value": "1"
},
Notice how the "meta_data" field is an array of objects and that these objects contain a "value" field. The data type of the "value" varies- sometimes it's an object and other times it's a string.
One possible solution would be to change the MetaDatum class so that the value is an Object:
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class MetaDatum {
...
#SerializedName("value")
#Expose
private Object value;
...
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
}

How do I map Retrofit response to Data Model Class?

Here is my Retrofit Call...
public void getContests() {
String token = LoginActivity.authToken;
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(OctoInterface.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
OctoInterface api = retrofit.create(OctoInterface.class);
Call<List<OctoModel2>> call = api.getOctoContests(token);
call.enqueue(new Callback<List<OctoModel2>>() {
#Override
public void onResponse(Call<List<OctoModel2>> call, Response<List<OctoModel2>> response) {
int statusCode = response.code();
int i = 0;
if (response.body().size() > titleList.size()) {
for (i = 0; i <= response.body().size() -1; i++) {
contestIdList.add(String.valueOf(response.body().get(i).getId()));
titleList.add(response.body().get(i).getTitle());
subtitleList.add(response.body().get(i).getDescShort());
offerIdList.add(String.valueOf(response.body().get(i).getId()));
offerLogoList.add(response.body().get(i).getLogoUrl());
businessId = String.valueOf(response.body().get(i).getBusinessId());
submit_button_text = response.body().get(i).getSubmitButtonText();
}
}
}
#Override
public void onFailure(Call<List<OctoModel2>> call, Throwable t) {
Log.e("Get Contest failure", call.toString());
t.printStackTrace();
}
});
}
As you can see, I'm currently grabbing the pieces of the response that I need and passing them to individual array lists. I'd much rather pass the entire return into a list of model objects that hold the data.
Here is my POJO class for retrofit...
public class OctoModel2 {
#SerializedName("how_it_works")
#Expose
private List<String> howItWorks = null;
#SerializedName("id")
#Expose
private int id;
#SerializedName("business_id")
#Expose
private int businessId;
#SerializedName("title")
#Expose
private String title;
#SerializedName("desc_short")
#Expose
private String descShort;
#SerializedName("logo_url")
#Expose
private String logoUrl;
#SerializedName("hashtag")
#Expose
private String hashtag;
#SerializedName("confirm_message_title")
#Expose
private String confirmMessageTitle;
#SerializedName("rules")
#Expose
private String rules;
#SerializedName("confirm_message")
#Expose
private String confirmMessage;
#SerializedName("start_date")
#Expose
private String startDate;
#SerializedName("end_date")
#Expose
private String endDate;
#SerializedName("active")
#Expose
private boolean active;
#SerializedName("entry_count")
#Expose
private int entryCount;
#SerializedName("age_required")
#Expose
private int ageRequired;
#SerializedName("submit_button_text")
#Expose
private String submitButtonText;
#SerializedName("hide_redeem_code")
#Expose
private boolean hideRedeemCode;
#SerializedName("redeem_button_text")
#Expose
private String redeemButtonText;
#SerializedName("rules_text")
#Expose
private String rulesText;
#SerializedName("mode")
#Expose
private String mode;
#SerializedName("entry_mode")
#Expose
private String entryMode;
#SerializedName("created_at")
#Expose
private String createdAt;
#SerializedName("updated_at")
#Expose
private String updatedAt;
#SerializedName("deleted_at")
#Expose
private Object deletedAt;
#SerializedName("locations")
#Expose
private List<Location> locations = null;
#SerializedName("entries")
#Expose
private List<Entry> entries = null;
#SerializedName("entry")
#Expose
private Entry entry;
#SerializedName("AWSAccessKeyId")
#Expose
private String aWSAccessKeyId;
#SerializedName("key")
#Expose
private String key;
#SerializedName("policy")
#Expose
private String policy;
#SerializedName("signature")
#Expose
private String signature;
#SerializedName("uuid")
#Expose
private String uuid;
#SerializedName("reward")
#Expose
private Reward reward;
#SerializedName("s3_url")
#Expose
private String s3_url;
public OctoModel2(Integer id, Integer businessId, String title, String descShort, String logoUrl, String hashtag, String confirmMessageTitle, String rules, String confirmMessage, String startDate, String endDate, Boolean active,
String submitButtonText, String redeemButtonText, String rulesText, List<Location> locations, String aWSAccessKeyId, String key, String policy, String signature, String uuid) {
this.id = id;
this.businessId = businessId;
this.title = title;
this.descShort = descShort;
this.logoUrl = logoUrl;
this.hashtag = hashtag;
this.confirmMessageTitle = confirmMessageTitle;
this.rules = rules;
this.confirmMessage = confirmMessage;
this.startDate = startDate;
this.endDate = endDate;
this.active = active;
this.submitButtonText = submitButtonText;
this.redeemButtonText = redeemButtonText;
this.rulesText = rulesText;
this.locations = locations;
this.aWSAccessKeyId = aWSAccessKeyId;
this.key = key;
this.policy = policy;
this.signature = signature;
this.uuid = uuid;
}
public List<String> getHowItWorks() {
return howItWorks;
}
public void setHowItWorks(List<String> howItWorks) {
this.howItWorks = howItWorks;
}
public int getId() {
return id;
}
public List<OctoModel2> getResults() {
return results;
}
public void setId(int id) {
this.id = id;
}
public int getBusinessId() {
return businessId;
}
public void setBusinessId(int businessId) {
this.businessId = businessId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescShort() {
return descShort;
}
public void setDescShort(String descShort) {
this.descShort = descShort;
}
public String getLogoUrl() {
return logoUrl;
}
public void setLogoUrl(String logoUrl) {
this.logoUrl = logoUrl;
}
public String getHashtag() {
return hashtag;
}
public void setHashtag(String hashtag) {
this.hashtag = hashtag;
}
public String getConfirmMessageTitle() {
return confirmMessageTitle;
}
public void setConfirmMessageTitle(String confirmMessageTitle) {
this.confirmMessageTitle = confirmMessageTitle;
}
public String getRules() {
return rules;
}
public void setRules(String rules) {
this.rules = rules;
}
public String getConfirmMessage() {
return confirmMessage;
}
public void setConfirmMessage(String confirmMessage) {
this.confirmMessage = confirmMessage;
}
public String getStartDate() {
return startDate;
}
public void setStartDate(String startDate) {
this.startDate = startDate;
}
public String getEndDate() {
return endDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public int getEntryCount() {
return entryCount;
}
public void setEntryCount(int entryCount) {
this.entryCount = entryCount;
}
public int getAgeRequired() {
return ageRequired;
}
public void setAgeRequired(int ageRequired) {
this.ageRequired = ageRequired;
}
public String getSubmitButtonText() {
return submitButtonText;
}
public void setSubmitButtonText(String submitButtonText) {
this.submitButtonText = submitButtonText;
}
public boolean isHideRedeemCode() {
return hideRedeemCode;
}
public void setHideRedeemCode(boolean hideRedeemCode) {
this.hideRedeemCode = hideRedeemCode;
}
public String getRedeemButtonText() {
return redeemButtonText;
}
public void setRedeemButtonText(String redeemButtonText) {
this.redeemButtonText = redeemButtonText;
}
public String getRulesText() {
return rulesText;
}
public void setRulesText(String rulesText) {
this.rulesText = rulesText;
}
public String getMode() {
return mode;
}
public void setMode(String mode) {
this.mode = mode;
}
public String getEntryMode() {
return entryMode;
}
public void setEntryMode(String entryMode) {
this.entryMode = entryMode;
}
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 Object getDeletedAt() {
return deletedAt;
}
public void setDeletedAt(Object deletedAt) {
this.deletedAt = deletedAt;
}
public List<Location> getLocations() {
return locations;
}
public void setLocations(List<Location> locations) {
this.locations = locations;
}
public List<Entry> getEntries() {
return entries;
}
public void setEntries(List<Entry> entries) {
this.entries = entries;
}
public Entry getEntry() {
return entry;
}
public String getAWSAccessKeyId() {
return aWSAccessKeyId;
}
public void setAWSAccessKeyId(String aWSAccessKeyId) {
this.aWSAccessKeyId = aWSAccessKeyId;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getPolicy() {
return policy;
}
public void setPolicy(String policy) {
this.policy = policy;
}
public String getSignature() {
return signature;
}
public String gets3url() {
return s3_url;
}
public void setSignature(String signature) {
this.signature = signature;
}
public Reward getReward() {
return reward;
}
public void setReward(Reward reward) {
this.reward = reward;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
}
Instead of calling the data from each list like
TitleList.get(position);
SubtitleList.get(position);
LogoUrlList.get(position);
etc...
I'd like to be able to call
Contests.get(position).getTitle();
Contests.get(position).getSubtitle();
Contests.get(position).getLogoUrl();
or however it would be. This would make it better for me to sort the responses and get the data from individual responses without hoping and praying that I'm pulling the correct item from the correct ArrayList.
You need a mapper that maps your DTO (Data Transfer Object) into an entity or list of entities. For example:
public interface Mapper<From, To> {
To map(From value);
}
Now you can create a class, e.g. called `MyRetrofitResponseMapper, that implements the interface and maps the fields needed.
Moreover, you can create multiple mappers that map the same DTO into different entities depending on what DTO fields are required for those.
An example can be found here.

Count duplicate items from custom object - android

I have a custom object list like bellow :
public List<Message> getMessages() {
return messages;
}
And :
public class Message {
#SerializedName("id")
#Expose
private String id;
#SerializedName("useridfrom")
#Expose
private String useridfrom;
#SerializedName("useridto")
#Expose
private String useridto;
#SerializedName("subject")
#Expose
private String subject;
#SerializedName("fullmessage")
#Expose
private String fullmessage;
#SerializedName("fullmessageformat")
#Expose
private String fullmessageformat;
#SerializedName("fullmessagehtml")
#Expose
private String fullmessagehtml;
#SerializedName("smallmessage")
#Expose
private String smallmessage;
#SerializedName("notification")
#Expose
private String notification;
#SerializedName("contexturl")
#Expose
private Object contexturl;
#SerializedName("contexturlname")
#Expose
private Object contexturlname;
#SerializedName("timecreated")
#Expose
private String timecreated;
#SerializedName("timeuserfromdeleted")
#Expose
private String timeuserfromdeleted;
#SerializedName("timeusertodeleted")
#Expose
private String timeusertodeleted;
#SerializedName("component")
#Expose
private String component;
#SerializedName("eventtype")
#Expose
private String eventtype;
#SerializedName("userfromfirstnamephonetic")
#Expose
private String userfromfirstnamephonetic;
#SerializedName("userfromlastnamephonetic")
#Expose
private String userfromlastnamephonetic;
#SerializedName("userfrommiddlename")
#Expose
private String userfrommiddlename;
#SerializedName("userfromalternatename")
#Expose
private String userfromalternatename;
#SerializedName("userfromfirstname")
#Expose
private String userfromfirstname;
#SerializedName("userfromlastname")
#Expose
private String userfromlastname;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUseridfrom() {
return useridfrom;
}
public void setUseridfrom(String useridfrom) {
this.useridfrom = useridfrom;
}
public String getUseridto() {
return useridto;
}
public void setUseridto(String useridto) {
this.useridto = useridto;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getFullmessage() {
return fullmessage;
}
public void setFullmessage(String fullmessage) {
this.fullmessage = fullmessage;
}
public String getFullmessageformat() {
return fullmessageformat;
}
public void setFullmessageformat(String fullmessageformat) {
this.fullmessageformat = fullmessageformat;
}
public String getFullmessagehtml() {
return fullmessagehtml;
}
public void setFullmessagehtml(String fullmessagehtml) {
this.fullmessagehtml = fullmessagehtml;
}
public String getSmallmessage() {
return smallmessage;
}
public void setSmallmessage(String smallmessage) {
this.smallmessage = smallmessage;
}
public String getNotification() {
return notification;
}
public void setNotification(String notification) {
this.notification = notification;
}
public Object getContexturl() {
return contexturl;
}
public void setContexturl(Object contexturl) {
this.contexturl = contexturl;
}
public Object getContexturlname() {
return contexturlname;
}
public void setContexturlname(Object contexturlname) {
this.contexturlname = contexturlname;
}
public String getTimecreated() {
return timecreated;
}
public void setTimecreated(String timecreated) {
this.timecreated = timecreated;
}
public String getTimeuserfromdeleted() {
return timeuserfromdeleted;
}
public void setTimeuserfromdeleted(String timeuserfromdeleted) {
this.timeuserfromdeleted = timeuserfromdeleted;
}
public String getTimeusertodeleted() {
return timeusertodeleted;
}
public void setTimeusertodeleted(String timeusertodeleted) {
this.timeusertodeleted = timeusertodeleted;
}
public String getComponent() {
return component;
}
public void setComponent(String component) {
this.component = component;
}
public String getEventtype() {
return eventtype;
}
public void setEventtype(String eventtype) {
this.eventtype = eventtype;
}
public String getUserfromfirstnamephonetic() {
return userfromfirstnamephonetic;
}
public void setUserfromfirstnamephonetic(String userfromfirstnamephonetic) {
this.userfromfirstnamephonetic = userfromfirstnamephonetic;
}
public String getUserfromlastnamephonetic() {
return userfromlastnamephonetic;
}
public void setUserfromlastnamephonetic(String userfromlastnamephonetic) {
this.userfromlastnamephonetic = userfromlastnamephonetic;
}
public String getUserfrommiddlename() {
return userfrommiddlename;
}
public void setUserfrommiddlename(String userfrommiddlename) {
this.userfrommiddlename = userfrommiddlename;
}
public String getUserfromalternatename() {
return userfromalternatename;
}
public void setUserfromalternatename(String userfromalternatename) {
this.userfromalternatename = userfromalternatename;
}
public String getUserfromfirstname() {
return userfromfirstname;
}
public void setUserfromfirstname(String userfromfirstname) {
this.userfromfirstname = userfromfirstname;
}
public String getUserfromlastname() {
return userfromlastname;
}
public void setUserfromlastname(String userfromlastname) {
this.userfromlastname = userfromlastname;
}
}
How can I count duplicate items : useridfrom and useridto.
I like use from RXJava for better performance an do in background.

Retrofit Help, always getting responseFailed

I have been trying to learn implementing Retrofit since past couple of days but I have been facing some issues. COuld someone pls help?
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Retrofit.Builder builder = new Retrofit.Builder().baseUrl("https://query.yahooapis.com") .addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
Details client = retrofit.create(Details.class);
Call<ArrayList<Condition>> call = client.reposForUser();
call.enqueue(new Callback<ArrayList<Condition>>() {
#Override
public void onResponse(Call<ArrayList<Condition>> call, Response<ArrayList<Condition>> response) {
Toast.makeText(MainActivity.this, "Yes", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<ArrayList<Condition>> call, Throwable t) {
Toast.makeText(MainActivity.this, "NO", Toast.LENGTH_SHORT).show();
System.out.print(t.getStackTrace().toString());
}
});
}
}
////////////////////////////////////////////////////////////////////////////
public interface Details {
#GET("/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22New%20Delhi%2CIndia%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys")
Call<ArrayList<Condition>> reposForUser();
}
///////////////////////////////////////////////////////////////////////////////
package hawkeyestudios.weatherretro;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Condition {
#SerializedName("code")
#Expose
private String code;
#SerializedName("date")
#Expose
private String date;
#SerializedName("temp")
#Expose
private String temp;
#SerializedName("text")
#Expose
private String text;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTemp() {
return temp;
}
public void setTemp(String temp) {
this.temp = temp;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
I made call to your API,based upon those json, I have segment the object.This is your Response class which holds the entire json, if you could request for Response class, you could get your json
public class Response {
#SerializedName("query")
#Expose
private Query query;
public Query getQuery() {
return query;
}
public void setQuery(Query query) {
this.query = query;
}
}
------------The Query class which holds the Result class------
public class Query {
#SerializedName("results")
#Expose
private Results results;
public Results getResults() {
return results;
}
public void setResults(Results results) {
this.results = results;
}
}
--------The result class which holds the Channels class
public class Results {
#SerializedName("channel")
#Expose
private Channel channel;
public Channel getChannel() {
return channel;
}
public void setChannel(Channel channel) {
this.channel = channel;
}
}
---This is the Channel class which holds the Item class
public class Channel {
#SerializedName("item")
#Expose
private Item item;
public Item getItem() {
return item;
}
public void setItem(Item item) {
this.item = item;
}
}
----This is the Item class which holds your actual data Condition which is not array but single object based upon your json response ---
public class Item {
#SerializedName("condition")
#Expose
private Condition condition;
public Condition getCondition() {
return condition;
}
public void setCondition(Condition condition) {
this.condition = condition;
}
}
-----Finally the Condition class
public class Condition {
#SerializedName("code")
#Expose
private String code;
#SerializedName("date")
#Expose
private String date;
#SerializedName("temp")
#Expose
private String temp;
#SerializedName("text")
#Expose
private String text;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTemp() {
return temp;
}
public void setTemp(String temp) {
this.temp = temp;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
//So finally make some change
call<Response> call = client.reposForUser();

Categories

Resources