I have following JSON string that I need to set to the Java objects of POJO class.
What method should I follow?
{"status":"FOUND","messages":null,"sharedLists": [{"listId":"391647d","listName":"/???","numberOfItems":0,"colla borative":false,"displaySettings":true}] }
I tried using Gson but it did not work for me.
Gson gson = new Gson();
SharedLists target = gson.fromJson(sb.toString(), SharedLists.class);
Following is my SharedLists pojo
public class SharedLists {
#SerializedName("listId")
private String listId;
#SerializedName("listName")
private String listName;
#SerializedName("numberOfItems")
private int numberOfItems;
#SerializedName("collaborative")
private boolean collaborative;
#SerializedName("displaySettings")
private boolean displaySettings;
public int getNumberOfItems() {
return numberOfItems;
}
public void setNumberOfItems(int numberOfItems) {
this.numberOfItems = numberOfItems;
}
public boolean isCollaborative() {
return collaborative;
}
public void setCollaborative(boolean collaborative) {
this.collaborative = collaborative;
}
public boolean isDisplaySettings() {
return displaySettings;
}
public void setDisplaySettings(boolean displaySettings) {
this.displaySettings = displaySettings;
}
public String getListId() {
return listId;
}
public void setListId(String listId) {
this.listId = listId;
}
}
Following is your JSON string.
{
"status": "FOUND",
"messages": null,
"sharedLists": [
{
"listId": "391647d",
"listName": "/???",
"numberOfItems": 0,
"colla borative": false,
"displaySettings": true
}
]
}
Clearly sharedLists is a JSON array within the outer JSON object.
So I have two classes as follows (created from http://www.jsonschema2pojo.org/ by providing your JSON as input)
ResponseObject - Represents the outer object
public class ResponseObject {
#SerializedName("status")
#Expose
private String status;
#SerializedName("messages")
#Expose
private Object messages;
#SerializedName("sharedLists")
#Expose
private List<SharedList> sharedLists = null;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Object getMessages() {
return messages;
}
public void setMessages(Object messages) {
this.messages = messages;
}
public List<SharedList> getSharedLists() {
return sharedLists;
}
public void setSharedLists(List<SharedList> sharedLists) {
this.sharedLists = sharedLists;
}
}
and the SharedList - Represents each object within the array
public class SharedList {
#SerializedName("listId")
#Expose
private String listId;
#SerializedName("listName")
#Expose
private String listName;
#SerializedName("numberOfItems")
#Expose
private Integer numberOfItems;
#SerializedName("colla borative")
#Expose
private Boolean collaBorative;
#SerializedName("displaySettings")
#Expose
private Boolean displaySettings;
public String getListId() {
return listId;
}
public void setListId(String listId) {
this.listId = listId;
}
public String getListName() {
return listName;
}
public void setListName(String listName) {
this.listName = listName;
}
public Integer getNumberOfItems() {
return numberOfItems;
}
public void setNumberOfItems(Integer numberOfItems) {
this.numberOfItems = numberOfItems;
}
public Boolean getCollaBorative() {
return collaBorative;
}
public void setCollaBorative(Boolean collaBorative) {
this.collaBorative = collaBorative;
}
public Boolean getDisplaySettings() {
return displaySettings;
}
public void setDisplaySettings(Boolean displaySettings) {
this.displaySettings = displaySettings;
}
}
Now you can parse the entire JSON string with GSON as follows
Gson gson = new Gson();
ResponseObject target = gson.fromJson(inputString, ResponseObject.class);
Hope this helps.
Related
I want to send array of objects like this to Spring REST Controller:
{
"measureList": [
{
"apiKey": "exampleKEY",
"stationId": "abcdef123",
"date": "2022-02-18T17:43:51.787535Z",
"temp": "20.5",
"humidity": "60.4",
"pressure": "1020.5",
"pm25": "100.0",
"pm25Corr": "150.0",
"pm10": "90.0"
},
{
"apiKey": "exampleKEY",
"stationId": "abcdef123",
"date": "2022-02-18T17:43:53.254309Z",
"temp": "20.5",
"humidity": "60.4",
"pressure": "1020.5",
"pm25": "100.0",
"pm25Corr": "150.0",
"pm10": "90.0"
}
]
}
I have created NewMeausurePackageDto like this:
package com.weather.server.domain.dto;
import java.util.ArrayList;
import java.util.List;
public class NewMeasurePackageDto {
private ArrayList<NewMeasureDto> measureList;
public NewMeasurePackageDto(ArrayList<NewMeasureDto> measureList) {
this.measureList = measureList;
}
public NewMeasurePackageDto() {
}
public ArrayList<NewMeasureDto> getNewMeasureListDto() {
return measureList;
}
#Override
public String toString() {
return "NewMeasurePackageDto{" +
"measureList=" + measureList +
'}';
}
}
NewMeasureDto class:
package com.weather.server.domain.dto;
public class NewMeasureDto {
private String apiKey;
private String stationId;
private String date;
private String temp;
private String humidity;
private String pressure;
private String pm25;
private String pm10;
private String pm25Corr;
//station_id
public NewMeasureDto() {
}
private NewMeasureDto(Builder builder){
apiKey = builder.apiKey;
stationId = builder.stationId;
date = builder.date;
temp = builder.temp;
humidity = builder.humidity;
pressure = builder.pressure;
pm25 = builder.pm25;
pm10 = builder.pm10;
pm25Corr = builder.pm25Corr;
}
public String getApiKey() {
return apiKey;
}
public String getStationID() {
return stationId;
}
public String getDate() {
return date;
}
public String getTemp() {
return temp;
}
public String getHumidity() {
return humidity;
}
public String getPressure() {
return pressure;
}
public String getPm25() {
return pm25;
}
public String getPm10() {
return pm10;
}
public String getPm25Corr() {
return pm25Corr;
}
public static final class Builder {
private String apiKey;
private String stationId;
private String date;
private String temp;
private String humidity;
private String pressure;
private String pm25;
private String pm10;
private String pm25Corr;
public Builder() {
}
public Builder apiKey(String apiKey) {
this.apiKey = apiKey;
return this;
}
public Builder stationID(String stationId) {
this.stationId = stationId;
return this;
}
public Builder date(String date) {
this.date = date;
return this;
}
public Builder temp(String temp) {
this.temp = temp;
return this;
}
public Builder humidity(String humidity) {
this.humidity = humidity;
return this;
}
public Builder pressure(String pressure){
this.pressure = pressure;
return this;
}
public Builder pm25(String pm25){
this.pm25 = pm25;
return this;
}
public Builder pm10(String pm10){
this.pm10 = pm10;
return this;
}
public Builder pm25Corr(String pm25Corr){
this.pm25Corr = pm25Corr;
return this;
}
public NewMeasureDto build() {
return new NewMeasureDto(this);
}
}
}
And request mapping in RestController:
#PostMapping(value="/new-measure-package") //addStation id
public ResponseEntity<Void> newMeasure(#RequestBody NewMeasurePackageDto measureList){
//if api key is valid
return measureService.saveMeasurePackage(measureList.getNewMeasureListDto()) ? new ResponseEntity<>(HttpStatus.OK) :
new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
With this code all I got is error about null measureList in Service function when trying to iterate over the list. I tried changing #RequestBody to
List<NewMeasureDto> measureList, and to Map<String, NewMeasureDto> measureList but still measureList is null or empty.
Thanks to ShaharT suggestion I found the answer.
There was missing setter in NewMeasurePackageDto, the class should look like this:
package com.weather.server.domain.dto;
import java.util.ArrayList;
public class NewMeasurePackageDto {
private ArrayList<NewMeasureDto> measureList;
public NewMeasurePackageDto(ArrayList<NewMeasureDto> measureList) {
this.measureList = measureList;
}
public NewMeasurePackageDto() {
}
public ArrayList<NewMeasureDto> getMeasureList() {
return measureList;
}
public void setMeasureList(ArrayList<NewMeasureDto> measureList) {
this.measureList = measureList;
}
#Override
public String toString() {
return "NewMeasurePackageDto{" +
"measureList=" + measureList +
'}';
}
}
Conclusion is: when dealing with object of arrays in JSON, there must be setter method for variable storing list in DTO.
[
{
"login": "mojombo",
"id": 1,
"node_id": "MDQ6VXNlcjE=",
"avatar_url": "https://avatars0.githubusercontent.com/u/1?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/mojombo",
"html_url": "https://github.com/mojombo",
"followers_url": "https://api.github.com/users/mojombo/followers",
"following_url": "https://api.github.com/users/mojombo/following{/other_user}",
"gists_url": "https://api.github.com/users/mojombo/gists{/gist_id}",
"starred_url": "https://api.github.com/users/mojombo/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/mojombo/subscriptions",
"organizations_url": "https://api.github.com/users/mojombo/orgs",
"repos_url": "https://api.github.com/users/mojombo/repos",
"events_url": "https://api.github.com/users/mojombo/events{/privacy}",
"received_events_url": "https://api.github.com/users/mojombo/received_events",
"type": "User",
"site_admin": false
}
]
Json: https://api.github.com/users
This is URL of an API... how can i parse this object to fetch the data using retrofit?
Here is the example on how to fetch JSON object with array using retrofit. I believe you won't have troubles changing it to work with your data.
Example.java
public class Example {
#SerializedName("PnrNumber")
#Expose
private String pnrNumber;
#SerializedName("Status")
#Expose
private String status;
#SerializedName("ResponseCode")
#Expose
private String responseCode;
#SerializedName("TrainNumber")
#Expose
private String trainNumber;
#SerializedName("TrainName")
#Expose
private String trainName;
#SerializedName("JourneyClass")
#Expose
private String journeyClass;
#SerializedName("ChatPrepared")
#Expose
private String chatPrepared;
#SerializedName("From")
#Expose
private String from;
#SerializedName("To")
#Expose
private String to;
#SerializedName("JourneyDate")
#Expose
private String journeyDate;
#SerializedName("Passangers")
#Expose
private List<Passanger> passangers = null;
public String getPnrNumber() {
return pnrNumber;
}
public void setPnrNumber(String pnrNumber) {
this.pnrNumber = pnrNumber;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getResponseCode() {
return responseCode;
}
public void setResponseCode(String responseCode) {
this.responseCode = responseCode;
}
public String getTrainNumber() {
return trainNumber;
}
public void setTrainNumber(String trainNumber) {
this.trainNumber = trainNumber;
}
public String getTrainName() {
return trainName;
}
public void setTrainName(String trainName) {
this.trainName = trainName;
}
public String getJourneyClass() {
return journeyClass;
}
public void setJourneyClass(String journeyClass) {
this.journeyClass = journeyClass;
}
public String getChatPrepared() {
return chatPrepared;
}
public void setChatPrepared(String chatPrepared) {
this.chatPrepared = chatPrepared;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getJourneyDate() {
return journeyDate;
}
public void setJourneyDate(String journeyDate) {
this.journeyDate = journeyDate;
}
public List<Passanger> getPassangers() {
return passangers;
}
public void setPassangers(List<Passanger> passangers) {
this.passangers = passangers;
}
}
Passanger.Java
public class Passanger {
#SerializedName("Passenger")
#Expose
private String passenger;
#SerializedName("BookingStatus")
#Expose
private String bookingStatus;
#SerializedName("CurrentStatus")
#Expose
private String currentStatus;
public String getPassenger() {
return passenger;
}
public void setPassenger(String passenger) {
this.passenger = passenger;
}
public String getBookingStatus() {
return bookingStatus;
}
public void setBookingStatus(String bookingStatus) {
this.bookingStatus = bookingStatus;
}
public String getCurrentStatus() {
return currentStatus;
}
public void setCurrentStatus(String currentStatus) {
this.currentStatus = currentStatus;
}
}
Here are the classes which are generated from the Response which you have provided in the question.
You can use this link to generate the POJO class for JSON response.
JSON TO POJO
Add this gradle:
implementation 'com.google.code.gson:gson:2.8.2'
Init the Gson buildr:
private Gson gson;
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("M/d/yy hh:mm a");
gson = gsonBuilder.create();
Parse the JSON using GSON
gson.fromJson(jsonObject.getJSONObject("data").toString(), Example.class);
These are the basic steps to parse the JSON using GSON.
For more information you can refer to the below article:
Parsing JSON on Android using GSON
Or Check the GSON official GitHub Repository
GSON
Here is my response from database
{
"error": false,
"images": [
{
"id": "9",
"url": "http://192.168.1.27/BimbinganPA/include//uploads/9.png"
}
]
}
my response class UserDataResponse.java (edited full data response)
#SerializedName("error")
#Expose
private String iserror;
#SerializedName("error_msg")
#Expose
private String error_msg;
#SerializedName("nama")
#Expose
private String nama;
#SerializedName("nomor_induk")
#Expose
private String nomor_induk;
#SerializedName("prodi")
#Expose
private String prodi;
#SerializedName("dosen_pa")
#Expose
private String dosen_pa;
#SerializedName("email")
#Expose
private String email;
#SerializedName("email2")
#Expose
private String email2;
#SerializedName("mobile_phone")
#Expose
private String mobile_phone;
#SerializedName("mobile_phone2")
#Expose
private String mobile_phone2;
#SerializedName("alamat_mlg")
#Expose
private String alamat_mlg;
#SerializedName("alamat_asal")
#Expose
private String alamat_asal;
#SerializedName("sma_asal")
#Expose
private String sma_asal;
#SerializedName("hobby")
#Expose
private String hobby;
#SerializedName("ekskul")
#Expose
private String ekskul;
#SerializedName("nama_ortu")
#Expose
private String nama_ortu;
#SerializedName("alamat_ortu")
#Expose
private String alamat_ortu;
#SerializedName("email_ortu")
#Expose
private String email_ortu;
#SerializedName("mobilephone_ortu")
#Expose
private String mobilephone_ortu;
#SerializedName("id_fb")
#Expose
private String id_fb;
#SerializedName("id_ig")
#Expose
private String id_ig;
#SerializedName("id_line")
#Expose
private String id_line;
#SerializedName("numb_wa")
#Expose
private String numb_wa;
#SerializedName("images")
#Expose
private List<Image> images = null;
public String getIserror() {
return iserror;
}
public void setIserror(String iserror) {
this.iserror = iserror;
}
public String getMsg() {
return error_msg;
}
public void setMsg(String error_msg) {
this.error_msg = error_msg;
}
public String getNama() {
return nama;
}
public void setNama(String nama) {
this.nama = nama;
}
public String getNomor_induk() {
return nomor_induk;
}
public void setNomor_induk(String nomor_induk) {
this.nomor_induk = nomor_induk;
}
public String getProdi() {
return prodi;
}
public void setProdi(String prodi) {
this.prodi = prodi;
}
public String getDosen_pa() {
return dosen_pa;
}
public void setDosen_pa(String dosen_pa) {
this.dosen_pa = dosen_pa;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail2() {
return email2;
}
public void setEmail2(String email2) {
this.email2 = email2;
}
public String getMobile_phone() {
return mobile_phone;
}
public void setMobile_phone(String mobile_phone) {
this.email = mobile_phone;
}
public String getMobile_phone2() {
return mobile_phone2;
}
public void setMobile_phone2(String mobile_phone2) {
this.email = mobile_phone2;
}
public String getAlamat_mlg() {
return alamat_mlg;
}
public void setAlamat_mlg(String alamat_mlg) {
this.alamat_mlg = alamat_mlg;
}
public String getAlamat_asal() {
return alamat_asal;
}
public void setAlamat_asal(String alamat_asal) {
this.alamat_asal = alamat_asal;
}
public String getSma_asal() {
return sma_asal;
}
public void setSma_asal(String sma_asal) {
this.sma_asal = sma_asal;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
public String getEkskul() {
return ekskul;
}
public void setEkskul(String ekskul) {
this.ekskul = ekskul;
}
public String getNama_ortu() {
return nama_ortu;
}
public void setNama_ortu(String nama_ortu) {
this.nama_ortu = nama_ortu;
}
public String getAlamat_ortu() {
return alamat_ortu;
}
public void setAlamat_ortu(String alamat_ortu) {
this.alamat_ortu = alamat_ortu;
}
public String getEmail_ortu() {
return email_ortu;
}
public void setEmail_ortu(String email_ortu) {
this.email_ortu = email_ortu;
}
public String getMobilephone_ortu() {
return mobilephone_ortu;
}
public void setMobilephone_ortu(String mobilephone_ortu) {
this.mobilephone_ortu = mobilephone_ortu;
}
public String getId_fb() {
return id_fb;
}
public void setId_fb(String id_fb) {
this.id_fb = id_fb;
}
public String getId_ig() {
return id_ig;
}
public void setId_ig(String id_ig) {
this.id_ig = id_ig;
}
public String getId_line() {
return id_line;
}
public void setId_line(String id_line) {
this.id_line = id_line;
}
public String getNumb_wa() {
return numb_wa;
}
public void setNumb_wa(String numb_wa) {
this.numb_wa = numb_wa;
}
public List<Image> getImages() {
return images;
}
here is my Image.class
#SerializedName("id")
#Expose
private String no_user_id;
#SerializedName("url")
#Expose
private String image_url;
public String getNo_user_id() {
return no_user_id;
}
public String getImage_url() {
return image_url;
}
this is how i call it
public void F0_getPhoto(){
Call<List<UserDataResponse>> getPhoto = mApiService.getImage(
String.valueOf(mPrefs.getUserID()));
getPhoto.enqueue(new Callback<List<UserDataResponse>>() {
#Override
public void onResponse(Call<List<UserDataResponse>> call, Response<List<UserDataResponse>>response) {
// String iserror = response.body().getIserror();
// Jika login berhasil maka data nama yang ada di response API
// akan diparsing ke activity selanjutnya.
List<UserDataResponse> userDatalist = response.body();
//Creating an String array for the ListView
String[] iserror = new String[userDatalist.size()];
//looping through all the heroes and inserting the names inside the string array
for (int i = 0; i < userDatalist.size(); i++) {
iserror[i] = userDatalist.get(i).getIserror();
if (iserror.equals("false")) {
String[] url = new String[userDatalist.size()];
url[i] = userDatalist.get(i).getImages().getimage_Url();
showPhoto(url);
}
}
#Override
public void onFailure(Call<List<UserDataResponse>> call, Throwable t){
Log.e("debug", "onFailure: ERROR > " + t.toString());
}
});
}
and my question is how i can call response "url" from array i tried to call method getimage_Url() after method getImage() but i cannot call it
url[i] = userDatalist.get(i).getImages().getimage_Url();
According your above json, it's return Object rather than Array. So, modify your F0_getPhoto to handle this.
public void F0_getPhoto(){
Call<UserDataResponse> getPhoto = mApiService.getImage(
String.valueOf(mPrefs.getUserID()));
getPhoto.enqueue(new Callback<UserDataResponse>() {
#Override
public void onResponse(Call<UserDataResponse> call, Response<UserDataResponse>response) {
// String iserror = response.body().getIserror();
// Jika login berhasil maka data nama yang ada di response API
// akan diparsing ke activity selanjutnya.
UserDataResponse userData = response.body();
//Creating an String array for the ListView
String error = userData.getIserror();
List<Image> images = userData.getImages();
String[] url = new String[images.size()];
//looping through all the heroes and inserting the names inside the string array
if (iserror.equals("false")) {
for (int i = 0; i < images.size(); i++) {
url[i] = images.getimage_Url();
}
showPhoto(url);
}
#Override
public void onFailure(Call<UserDataResponse> call, Throwable t){
Log.e("debug", "onFailure: ERROR > " + t.toString());
}
});
}
}
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;
}
}
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.