ObjectMapper can't map the variables of inner class - java

ObjectMapper mapper = new ObjectMapper();
try {
attractionMainResponse = mapper.readValue(response,AttractionMainResponse.class);
} catch(IOException io) {
showToast("Something went wrong");
FirebaseCrash.log(io.toString());
finish();
}
AttractionMainResponse :
#JsonIgnoreProperties (ignoreUnknown = true)
public class AttractionMainResponse {
private AttractionDetailModel Attraction_Info;
private String response;
public AttractionMainResponse() {
Attraction_Info = null;
response =null;
}
public AttractionMainResponse(AttractionDetailModel aa,String ab) {
Attraction_Info = aa;
response = ab;
}
public AttractionDetailModel getAttraction_Info() {
return Attraction_Info;
}
public void setAttraction_Info(AttractionDetailModel attraction_Info) {
Attraction_Info = attraction_Info;
}
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
}
AttractionDetailModel :
#JsonIgnoreProperties (ignoreUnknown = true)
public class AttractionDetailModel {
private AddressDataAttraction address_data;
private List<Image> Images;
private TypesInAttraction Type;
private String architect;
private String architectural_style;
private int city_id;
private String founder;
private String description;
private int id;
private String name;
private String height;
private String opened_since;
private String popularity;
private String timings;
private String visitors;
private String profile_image_url;
public AttractionDetailModel() {
address_data = null;
architect = null;
architectural_style = null;
city_id=-1;
founder = null;
description = null;
id=-1;
name=null;
height=null;
opened_since=null;
popularity = null;
timings=null;
visitors=null;
Images = null;
Type=null;
profile_image_url=null;
}
public AttractionDetailModel(AddressDataAttraction address_data, List<Image> images, TypesInAttraction type, String architect, String architectural_style, int city_id, String founder, String description, int id, String name, String height, String opened_since, String popularity, String timings, String visitors, String profile_image_url) {
this.address_data = address_data;
Images = images;
Type = type;
this.architect = architect;
this.architectural_style = architectural_style;
this.city_id = city_id;
this.founder = founder;
this.description = description;
this.id = id;
this.name = name;
this.height = height;
this.opened_since = opened_since;
this.popularity = popularity;
this.timings = timings;
this.visitors = visitors;
this.profile_image_url = profile_image_url;
}
public String getProfile_image_url() {
return profile_image_url;
}
public void setProfile_image_url(String profile_image_url) {
this.profile_image_url = profile_image_url;
}
public AddressDataAttraction getAddress_data() {
return address_data;
}
public void setAddress_data(AddressDataAttraction address_data) {
this.address_data = address_data;
}
public List<Image> getImages() {
return Images;
}
public void setImages(List<Image> images) {
Images = images;
}
public TypesInAttraction getType() {
return Type;
}
public void setType(TypesInAttraction type) {
Type = type;
}
public String getArchitect() {
return architect;
}
public void setArchitect(String architect) {
this.architect = architect;
}
public String getArchitectural_style() {
return architectural_style;
}
public void setArchitectural_style(String architectural_style) {
this.architectural_style = architectural_style;
}
public int getCity_id() {
return city_id;
}
public void setCity_id(int city_id) {
this.city_id = city_id;
}
public String getFounder() {
return founder;
}
public void setFounder(String founder) {
this.founder = founder;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getOpened_since() {
return opened_since;
}
public void setOpened_since(String opened_since) {
this.opened_since = opened_since;
}
public String getPopularity() {
return popularity;
}
public void setPopularity(String popularity) {
this.popularity = popularity;
}
public String getTimings() {
return timings;
}
public void setTimings(String timings) {
this.timings = timings;
}
public String getVisitors() {
return visitors;
}
public void setVisitors(String visitors) {
this.visitors = visitors;
}
}
AddressDataAttractions :
#JsonIgnoreProperties (ignoreUnknown = true)
public class AddressDataAttraction {
private String address;
private String city;
private String country;
private String landmark;
private float latitude;
private float longitude;
private String pincode;
private String state;
public AddressDataAttraction() {
address=null;
city=null;
country=null;
landmark=null;
latitude=-1;
longitude=-1;
pincode=null;
state=null;
}
public AddressDataAttraction(String address, String city, String country, String landmark, float latitude, float longitude, String pincode, String state) {
this.address = address;
this.city = city;
this.country = country;
this.landmark = landmark;
this.latitude = latitude;
this.longitude = longitude;
this.pincode = pincode;
this.state = state;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getLandmark() {
return landmark;
}
public void setLandmark(String landmark) {
this.landmark = landmark;
}
public float getLatitude() {
return latitude;
}
public void setLatitude(float latitude) {
this.latitude = latitude;
}
public float getLongitude() {
return longitude;
}
public void setLongitude(float longitude) {
this.longitude = longitude;
}
public String getPincode() {
return pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
TypeInAttraction :
#JsonIgnoreProperties (ignoreUnknown = true)
public class TypesInAttraction{
private String type;
private int id ;
public TypesInAttraction() {
type=null;
id=-1;
}
public TypesInAttraction(String type, int id) {
this.type = type;
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
In debug mode, string response in objectMapper shows correct response, string response in attractionMainResponse giving a success but can't map the attractionDetailModel, giving null.

Is this about a Jackson ObjectMapper? Is it possible to create a smaller example, that makes it easier to give a solution.

Related

How to Fetch data from API using Retrofit in Android

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

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.

Cant get the getUrl() in to onBindViewHolder?

I have a ListSourceAdapter.java class,
class ListSourceViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ItemClickListener itemClickListener;
TextView source_title;
CircleImageView source_image;
public ListSourceViewHolder(View itemView) {
super(itemView);
source_title = (TextView) itemView.findViewById(R.id.source_name);
source_image = (CircleImageView) itemView.findViewById(R.id.source_image);
}
#Override
public void onClick(View v) {
itemClickListener.onClick(v, getAdapterPosition(), false);
}
}
public class ListSourceAdapter extends RecyclerView.Adapter<ListSourceViewHolder> {
private Context context;
private WebSite webSite;
public ListSourceAdapter(Context context, WebSite webSite) {
this.context = context;
this.webSite = webSite;
}
#Override
public ListSourceViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View itemView = inflater.inflate(R.layout.source_layout, parent, false);
return new ListSourceViewHolder(itemView);
}
#Override
public void onBindViewHolder(ListSourceViewHolder holder, int position) {
StringBuilder iconBetterAPI = new StringBuilder("https://icons.better-idea.org/allicons.json?url=");
iconBetterAPI.append(webSite.getSources().get(position).getUrl());
}
#Override
public int getItemCount() {
return webSite.getSources().size();
}
}
in onBindView Im try to use getUrl() but it says cannot resolve method
my WebSite.java model class like below
public class WebSite {
private String status;
private List<Source> sources;
public WebSite() {
}
public WebSite(String status, List<Source> sources) {
this.status = status;
this.sources = sources;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public List<Source> getSources() {
return sources;
}
public void setSources(List<Source> sources) {
this.sources = sources;
}
}
Source.java file like below
class UrlsToLogs {
private String small, medium, large;
public String getSmall() {
return small;
}
public void setSmall(String small) {
this.small = small;
}
public String getMedium() {
return medium;
}
public void setMedium(String medium) {
this.medium = medium;
}
public String getLarge() {
return large;
}
public void setLarge(String large) {
this.large = large;
}
}
public class Source {
private String id, name, description, url, category, language, country;
private UrlsToLogs urlsToLogs;
private List<String> sortByAvailable;
public Source() {
}
public Source(String id, String name, String description, String url, String category, String language, String country, UrlsToLogs urlsToLogs, List<String> sortByAvailable) {
this.id = id;
this.name = name;
this.description = description;
this.url = url;
this.category = category;
this.language = language;
this.country = country;
this.urlsToLogs = urlsToLogs;
this.sortByAvailable = sortByAvailable;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public UrlsToLogs getUrlsToLogs() {
return urlsToLogs;
}
public void setUrlsToLogs(UrlsToLogs urlsToLogs) {
this.urlsToLogs = urlsToLogs;
}
public List<String> getSortByAvailable() {
return sortByAvailable;
}
public void setSortByAvailable(List<String> sortByAvailable) {
this.sortByAvailable = sortByAvailable;
}
}
IconBetterIdeaService interface like below
public interface IconBetterIdeaService {
#GET
Call<IconBetterIdea> getIconUrl(#Url String url);
}
ItemClickListner interface like below
public interface ItemClickListener {
void onClick(View view, int position, boolean isLongClick);
}
why I can't access getUrl(), what did I do wrong in my code?
Try this create separate class like this
public class WebSite {
private String status;
private List<Source> sources;
public WebSite() {
}
public WebSite(String status, List<Source> sources) {
this.status = status;
this.sources = sources;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public List<Source> getSources() {
return sources;
}
public void setSources(List<Source> sources) {
this.sources = sources;
}
}
than
public class Source {
private String id, name, description, url, category, language, country;
private UrlsToLogs urlsToLogs;
private List<String> sortByAvailable;
public Source() {
}
public Source(String id, String name, String description, String url, String category, String language, String country, UrlsToLogs urlsToLogs, List<String> sortByAvailable) {
this.id = id;
this.name = name;
this.description = description;
this.url = url;
this.category = category;
this.language = language;
this.country = country;
this.urlsToLogs = urlsToLogs;
this.sortByAvailable = sortByAvailable;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public UrlsToLogs getUrlsToLogs() {
return urlsToLogs;
}
public void setUrlsToLogs(UrlsToLogs urlsToLogs) {
this.urlsToLogs = urlsToLogs;
}
public List<String> getSortByAvailable() {
return sortByAvailable;
}
public void setSortByAvailable(List<String> sortByAvailable) {
this.sortByAvailable = sortByAvailable;
}
}
than
public class UrlsToLogs {
private String small, medium, large;
public String getSmall() {
return small;
}
public void setSmall(String small) {
this.small = small;
}
public String getMedium() {
return medium;
}
public void setMedium(String medium) {
this.medium = medium;
}
public String getLarge() {
return large;
}
public void setLarge(String large) {
this.large = large;
}
}
OUTPUT
Clear-Rebuild and also check the imports

Java Object Serialization to JSON using Jackson

I have the following POJO classes
#JsonIgnoreProperties(ignoreUnknown = true)
public class GroupUser {
#JsonProperty("userId")
int userId;
#JsonProperty("status")
int status;
#JsonProperty("admin")
int isAdmin;
#JsonProperty("email")
String email;
#JsonProperty("creator")
int Creator;
#JsonProperty("new")
int isNew;
// generated and cached
#JsonProperty("user_name")
String userName;
public GroupUser() {
}
#JsonIgnore
public GroupUser(String email, int isCreator) {
this.userId = 0;
this.email = email;
this.Creator = isCreator;
this.isAdmin = isCreator;
if (isCreator == 1) {
this.status = Group.STATE_ACCEPTED;
this.isNew = 0;
} else {
this.isNew = 1;
this.status = Group.STATE_INVITED;
}
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public int getIsAdmin() {
return isAdmin;
}
public void setIsAdmin(int isAdmin) {
this.isAdmin = isAdmin;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getCreator() {
return Creator;
}
public void setCreator(int creator) {
Creator = creator;
}
public int getIsNew() {
return isNew;
}
public void setIsNew(int isNew) {
this.isNew = isNew;
}
}
And
#JsonIgnoreProperties(ignoreUnknown = true)
public class Group {
#JsonIgnore
final public static int STATE_INVITED = 1;
#JsonIgnore
final public static int STATE_REJECTED = 2;
#JsonIgnore
final public static int STATE_ACCEPTED = 3;
#JsonIgnore
final public static int STATE_PENDING = 4;
#JsonProperty("location")
String location;
#JsonProperty("radius")
int radius;
#JsonProperty("adminApprovalForObservers")
int isAdminApprovalRequired;
#JsonProperty("title")
String Title;
#JsonProperty("groupUsers")
GroupUser[] Users;
#JsonProperty("newVotingOnlyByAdmin")
int onlyAdminCreatesVote;
#JsonProperty("new")
int isNew;
#JsonProperty("requiredVotes")
int requiredVotes;
#JsonProperty("type")
int type;
#JsonProperty("allowObservers")
int allowObservers;
#JsonProperty("thumb")
String imageUrl;
#JsonProperty("timestamp")
long timeStamp;
#JsonProperty("openForAnyone")
int isOpenForAnyone;
#JsonProperty("uniqueId")
String uiqueId;
#JsonProperty("newDecisionOnlyByAdmin")
int newDecisionOnlyByAdmin;
#JsonProperty("requirePresence")
int requirePresence;
#JsonProperty("groupId")
int groupId;
#JsonProperty("automaticExclusions")
int autoExclusion;
#JsonProperty("adminApprovalForMembership")
int adminApprovalForMembership;
#JsonProperty("description")
String description;
// generated and cached
#JsonProperty("creator_name")
String creatorName;
public Group() {
}
#JsonIgnore
public Group(int id) {
this.groupId = id;
}
#JsonIgnore
public Group(String name, String description, String imagePath) {
this.Title = name;
this.description = description;
this.groupId = 0;
this.location = "";
this.radius = 0;
this.imageUrl = imagePath;
this.isNew = 1;
this.Users = new GroupUser[] {};
this.isOpenForAnyone = 1;
this.onlyAdminCreatesVote = 0;
this.adminApprovalForMembership = 0;
this.allowObservers = 1;
this.timeStamp = Calendar.getInstance().getTimeInMillis() / 1000;
}
#JsonIgnore
public String getCreatorsEmail() {
for (GroupUser u : Users) {
if (u.getCreator() == 1) {
return u.getEmail();
}
}
return null;
}
#JsonIgnore
public int getCreatorsId() {
for (GroupUser u : Users) {
if (u.getCreator() == 1) {
return u.getUserId();
}
}
return -1;
}
#JsonIgnore
public GroupUser getUser(int userId) {
if (Users != null) {
for (GroupUser gu : Users) {
if (gu.getUserId() == userId) {
return gu;
}
}
}
return null;
}
public String getCreatorName() {
return creatorName;
}
public void setCreatorName(String creatorName) {
this.creatorName = creatorName;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public int getRadius() {
return radius;
}
public void setRadius(int radius) {
this.radius = radius;
}
public int getIsAdminApprovalRequired() {
return isAdminApprovalRequired;
}
public void setIsAdminApprovalRequired(int isAdminApprovalRequired) {
this.isAdminApprovalRequired = isAdminApprovalRequired;
}
public String getTitle() {
return Title;
}
public void setTitle(String title) {
Title = title;
}
#JsonProperty("groupUsers")
public GroupUser[] getUsers() {
return Users;
}
#JsonProperty("groupUsers")
public void setUsers(GroupUser[] users) {
Users = users;
}
public int getOnlyAdminCreatesVote() {
return onlyAdminCreatesVote;
}
public void setOnlyAdminCreatesVote(int onlyAdminCreatesVote) {
this.onlyAdminCreatesVote = onlyAdminCreatesVote;
}
public int getIsNew() {
return isNew;
}
public void setIsNew(int isNew) {
this.isNew = isNew;
}
public int getRequiredVotes() {
return requiredVotes;
}
public void setRequiredVotes(int requiredVotes) {
this.requiredVotes = requiredVotes;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public int getAllowObservers() {
return allowObservers;
}
public void setAllowObservers(int allowObservers) {
this.allowObservers = allowObservers;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public long getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(long timeStamp) {
this.timeStamp = timeStamp;
}
public int getIsOpenForAnyone() {
return isOpenForAnyone;
}
public void setIsOpenForAnyone(int isOpenForAnyone) {
this.isOpenForAnyone = isOpenForAnyone;
}
public String getUiqueId() {
return uiqueId;
}
public void setUiqueId(String uiqueId) {
this.uiqueId = uiqueId;
}
public int getNewDecisionOnlyByAdmin() {
return newDecisionOnlyByAdmin;
}
public void setNewDecisionOnlyByAdmin(int newDecisionOnlyByAdmin) {
this.newDecisionOnlyByAdmin = newDecisionOnlyByAdmin;
}
public int getRequirePresence() {
return requirePresence;
}
public void setRequirePresence(int requirePresence) {
this.requirePresence = requirePresence;
}
public int getGroupId() {
return groupId;
}
public void setGroupId(int groupId) {
this.groupId = groupId;
}
public int getAutoExclusion() {
return autoExclusion;
}
public void setAutoExclusion(int autoExclusion) {
this.autoExclusion = autoExclusion;
}
public int getAdminApprovalForMembership() {
return adminApprovalForMembership;
}
public void setAdminApprovalForMembership(int adminApprovalForMembership) {
this.adminApprovalForMembership = adminApprovalForMembership;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
I am using jackson library to serialize the Group Object to JSON like below:
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, true);
return mapper.writeValueAsString(group);
But the Users fields never gets serialized, no matter what groupUsers always is an empty array []. Any idea what am I doing wrong?

Categories

Resources