I am very new to JSON and jackson, currently I have pojo files and I am trying to get the data and store it in an array. for example I want to extract Network name and store it an array and later display or compare it with live site data.
here is the main pojo file -
public class JsonGen{
private String _type;
private List cast;
private List clips;
private Common_sense_data common_sense_data;
private String common_sense_id;
private List crew;
private String description;
private List episodes;
private Number franchise_id;
private List genres;
private String guid;
private Images images;
private boolean is_locked;
private boolean is_mobile;
private boolean is_parental_locked;
private String kind;
private List mobile_networks;
private String most_recent_full_episode_added_date;
private String name;
private List networks;
private List platforms;
private List ratings;
private String release_date;
private List season_filters;
private String slug;
private String tms_id;
public String get_type(){
return this._type;
}
public void set_type(String _type){
this._type = _type;
}
public List getCast(){
return this.cast;
}
public void setCast(List cast){
this.cast = cast;
}
public List getClips(){
return this.clips;
}
public void setClips(List clips){
this.clips = clips;
}
public Common_sense_data getCommon_sense_data(){
return this.common_sense_data;
}
public void setCommon_sense_data(Common_sense_data common_sense_data){
this.common_sense_data = common_sense_data;
}
public String getCommon_sense_id(){
return this.common_sense_id;
}
public void setCommon_sense_id(String common_sense_id){
this.common_sense_id = common_sense_id;
}
public List getCrew(){
return this.crew;
}
public void setCrew(List crew){
this.crew = crew;
}
public String getDescription(){
return this.description;
}
public void setDescription(String description){
this.description = description;
}
public List getEpisodes(){
return this.episodes;
}
public void setEpisodes(List episodes){
this.episodes = episodes;
}
public Number getFranchise_id(){
return this.franchise_id;
}
public void setFranchise_id(Number franchise_id){
this.franchise_id = franchise_id;
}
public List getGenres(){
return this.genres;
}
public void setGenres(List genres){
this.genres = genres;
}
public String getGuid(){
return this.guid;
}
public void setGuid(String guid){
this.guid = guid;
}
public Images getImages(){
return this.images;
}
public void setImages(Images images){
this.images = images;
}
public boolean getIs_locked(){
return this.is_locked;
}
public void setIs_locked(boolean is_locked){
this.is_locked = is_locked;
}
public boolean getIs_mobile(){
return this.is_mobile;
}
public void setIs_mobile(boolean is_mobile){
this.is_mobile = is_mobile;
}
public boolean getIs_parental_locked(){
return this.is_parental_locked;
}
public void setIs_parental_locked(boolean is_parental_locked){
this.is_parental_locked = is_parental_locked;
}
public String getKind(){
return this.kind;
}
public void setKind(String kind){
this.kind = kind;
}
public List getMobile_networks(){
return this.mobile_networks;
}
public void setMobile_networks(List mobile_networks){
this.mobile_networks = mobile_networks;
}
public String getMost_recent_full_episode_added_date(){
return this.most_recent_full_episode_added_date;
}
public void setMost_recent_full_episode_added_date(String most_recent_full_episode_added_date){
this.most_recent_full_episode_added_date = most_recent_full_episode_added_date;
}
public String getName(){
return this.name;
}
public void setName(String name){
this.name = name;
}
public List getNetworks(){
return this.networks;
}
public void setNetworks(List networks){
this.networks = networks;
}
public List getPlatforms(){
return this.platforms;
}
public void setPlatforms(List platforms){
this.platforms = platforms;
}
public List getRatings(){
return this.ratings;
}
public void setRatings(List ratings){
this.ratings = ratings;
}
public String getRelease_date(){
return this.release_date;
}
public void setRelease_date(String release_date){
this.release_date = release_date;
}
public List getSeason_filters(){
return this.season_filters;
}
public void setSeason_filters(List season_filters){
this.season_filters = season_filters;
}
public String getSlug(){
return this.slug;
}
public void setSlug(String slug){
this.slug = slug;
}
public String getTms_id(){
return this.tms_id;
}
public void setTms_id(String tms_id){
this.tms_id = tms_id;
}
}
here is the Network Pojo class -
public class Networks{
private String banner;
private String description;
private boolean is_locked;
private String logo;
private String name;
private String network_analytics;
private Number network_id;
private String slug;
private String thumbnail_url;
private String url;
public String getBanner(){
return this.banner;
}
public void setBanner(String banner){
this.banner = banner;
}
public String getDescription(){
return this.description;
}
public void setDescription(String description){
this.description = description;
}
public boolean getIs_locked(){
return this.is_locked;
}
public void setIs_locked(boolean is_locked){
this.is_locked = is_locked;
}
public String getLogo(){
return this.logo;
}
public void setLogo(String logo){
this.logo = logo;
}
public String getName(){
return this.name;
}
public void setName(String name){
this.name = name;
}
public String getNetwork_analytics(){
return this.network_analytics;
}
public void setNetwork_analytics(String network_analytics){
this.network_analytics = network_analytics;
}
public Number getNetwork_id(){
return this.network_id;
}
public void setNetwork_id(Number network_id){
this.network_id = network_id;
}
public String getSlug(){
return this.slug;
}
public void setSlug(String slug){
this.slug = slug;
}
public String getThumbnail_url(){
return this.thumbnail_url;
}
public void setThumbnail_url(String thumbnail_url){
this.thumbnail_url = thumbnail_url;
}
public String getUrl(){
return this.url;
}
public void setUrl(String url){
this.url = url;
}
}
and here is my code through which I am trying to extract the network names -
public class util {
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
List<JsonGen> jsongenShow = null;
String url1 = "http://www.dishanywhere.com/radish/v20/dol/home/carousels/shows.json";
getShowNWGopherParser(nwork, url1);
}
public static String[] getShowNWGopherParser (List<Networks> nwork, String url ) throws JsonParseException, JsonMappingException, IOException
{
URL jsonUrl = new URL(url);
ObjectMapper objmapper = new ObjectMapper();
//objmapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
nwork = objmapper.readValue(jsonUrl, new TypeReference<List<Networks>>() {});
String [] shows = new String [nwork.size()];
int i = 0;
for(Networks element : nwork) {
shows[i++]=element.getUrl();
}
for(int j =0; j<shows.length;j++)
{
System.out.println(shows[j]);
}
return shows;
}
}
and here is the error -
Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "networks" (class featureshows.Networks), not marked as ignorable (10 known properties: , "logo", "slug", "name", "banner", "network_id", "url", "network_analytics", "description", "thumbnail_url", "is_locked"])
at [Source: http://www.dishanywhere.com/radish/v20/dol/home/carousels/shows.json; line: 1, column: 15] (through reference chain: featureshows.Networks["networks"])
at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:79)
at com.fasterxml.jackson.databind.DeserializationContext.reportUnknownProperty(DeserializationContext.java:568)
at com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:650)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:830)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:310)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:112)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:226)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:203)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:23)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2563)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:1789)
at functions.util.getShowNWGopherParser(util.java:77)
at functions.util.main(util.java:31)
The reason is that you're using a regular List interface for your list of networks instead of the generic version with the bounds for the expected type.
Try changing the field declaration from:
private List networks;
to
private List<Networks> networks;
While you're at it, it looks like you're using the regular List interface pretty much everywhere. You'll probably run into more issues if you don't convert them all to include the type you expect in the list.
Essentially, you're not providing enough information about the type of object you expect in the list for jackson to figure out what to populate it with. You can read more about generics here: http://docs.oracle.com/javase/tutorial/extra/generics/intro.html
EDIT:
It looks (from your comment) that you've already tried disabling checks for unknown properties, but try adding this annotation to your Networks class:
#JsonIgnoreProperties(ignoreUnknown = true)
Related
I'm trying to use New York Times API with Retrofit using Observable. But I'm getting this error when trying to use datas.
Can someone help me see where I'm wrong, please ?
Here is my ApiServices interface:
#GET("svc/topstories/v2/home.json?api-key=HiddenApiKeyJustForThisMessage")
Observable<TopStoryResult> getTopStories();
#GET("svc/topstories/v2/home.json?api-key=HiddenApiKeyJustForThisMessage")
Observable<List<NewsItem>> getResults();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.nytimes.com/")
.addConverterFactory(GsonConverterFactory.create(new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
Here is my ApiStreams class
public static Observable<TopStoryResult> streamFetchTopStories(){
ApiServices mApiServices = ApiServices.retrofit.create(ApiServices.class);
return mApiServices.getTopStories()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.timeout(10, TimeUnit.SECONDS);
}
public static Observable<List<NewsItem>> streamFetchNews(){
ApiServices mApiServices = ApiServices.retrofit.create(ApiServices.class);
return mApiServices.getResults()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.timeout(10, TimeUnit.SECONDS);
}
And this is what I'm trying to do in my MainActivity. For now I just want to display in a TextView the list of each Title...
//------------------------
// Update UI
//------------------------
private void updateUIWhenStartingHttpRequest() {
this.textView.setText("Downloading...");
}
private void updateUIWhenStopingHttpRequest(String response) {
this.textView.setText(response);
}
//------------------------
// Rx Java
//------------------------
private void executeRequestWithRetrofit(){
this.updateUIWhenStartingHttpRequest();
this.disposable = ApiStreams.streamFetchNews()
.subscribeWith(new DisposableObserver<List<NewsItem>>(){
#Override
public void onNext(List<NewsItem> topStories) {
Log.e("TAG", "On Next");
updateUIWithResult(topStories);
}
#Override
public void onError(Throwable e) {
Log.e("ERROR", Log.getStackTraceString(e));
}
#Override
public void onComplete() {
Log.e("TAG", "On Complete !");
}
});
}
private void updateUIWithResult(List<NewsItem> newsItemList){
StringBuilder mStringBuilder = new StringBuilder();
for (NewsItem news : newsItemList){
Log.e("TAG", "UPDATE UI" + news.getTitle());
mStringBuilder.append("- " + news.getTitle() + "\n");
}
updateUIWhenStopingHttpRequest(mStringBuilder.toString());
}
[EDIT]
There are my two models for TopStories and NewsItem
TopStories:
private String status;
private String copyright;
private String section;
private String lastUpdated;
private Integer numResults;
private List<NewsItem> results = null;
public String getStatus() {return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getCopyright() {
return copyright;
}
public void setCopyright(String copyright) {
this.copyright = copyright;
}
public String getSection() {
return section;
}
public void setSection(String section) {
this.section = section;
}
public String getLastUpdated() {
return lastUpdated;
}
public void setLastUpdated(String lastUpdated) {
this.lastUpdated = lastUpdated;
}
public Integer getNumResults() {
return numResults;
}
public void setNumResults(Integer numResults) {
this.numResults = numResults;
}
public List<NewsItem> getResults() {
return results;
}
public void setResults(List<NewsItem> results) {
this.results = results;
}
NewsItem:
private String section;
private String subsection;
private String title;
private String url;
private String byline;
private String updated_date;
private String created_date;
private String published_date;
private String material_type_facet;
private String kicker;
#SerializedName("abstract")
private String abstract_string;
private List<Multimedia> multimedia;
private transient String des_facet;
private transient String org_facet;
private transient String per_facet;
private transient String geo_facet;
public NewsItem() {
}
public NewsItem(String url) {
this.url = url;
}
public NewsItem(String section, String subsection, String title, String url, String byline, String updated_date, String created_date, String published_date, String material_type_facet, String kicker) {
this.section = section;
this.subsection = subsection;
this.title = title;
this.url = url;
this.byline = byline;
this.updated_date = updated_date;
this.created_date = created_date;
this.published_date = published_date;
this.material_type_facet = material_type_facet;
this.kicker = kicker;
}
public String getSection() {
return section;
}
public void setSection(String section) {
this.section = section;
}
public String getSubsection() {
return subsection;
}
public void setSubsection(String subsection) {
this.subsection = subsection;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getByline() {
return byline;
}
public void setByline(String byline) {
this.byline = byline;
}
public String getUpdated_date() {
return updated_date;
}
public void setUpdated_date(String updated_date) {
this.updated_date = updated_date;
}
public String getCreated_date() {
return created_date;
}
public void setCreated_date(String created_date) {
this.created_date = created_date;
}
public String getPublished_date() {
return published_date;
}
public void setPublished_date(String published_date) {
this.published_date = published_date;
}
public String getMaterial_type_facet() {
return material_type_facet;
}
public void setMaterial_type_facet(String material_type_facet) {
this.material_type_facet = material_type_facet;
}
public String getKicker() {
return kicker;
}
public void setKicker(String kicker) {
this.kicker = kicker;
}
public String getAbstract() {
return abstract_string;
}
public void setAbstract(String abstract_string) {
this.abstract_string = abstract_string;
}
public List<Multimedia> getMultimedia() {
return multimedia;
}
public void setMultimedia(List<Multimedia> multimedia) {
this.multimedia = multimedia;
}
public String getDes_facet() {
return des_facet;
}
public void setDes_facet(String des_facet) {
this.des_facet = des_facet;
}
public String getOrg_facet() {
return org_facet;
}
public void setOrg_facet(String org_facet) {
this.org_facet = org_facet;
}
public String getPer_facet() {
return per_facet;
}
public void setPer_facet(String per_facet) {
this.per_facet = per_facet;
}
public String getGeo_facet() {
return geo_facet;
}
public void setGeo_facet(String geo_facet) {
this.geo_facet = geo_facet;
}
Here is what the JSON looks like:
JSON
First when I tried this one with Github user API, it works fine. But I can't figure out where I'm wrong there...
Is anybody can help me please ?
Thanks a lot !
Expected BEGIN_ARRAY but was BEGIN_OBJECT
this means you are trying to a get a JSON Array as a List in JAVA but the api sent you a JSON OBJECT. So I cannot gather enough information but if I have to guess you should change this
#GET("svc/topstories/v2/home.json?api-key=HiddenApiKeyJustForThisMessage")
Observable<List<NewsItem>> getResults();
to
#GET("svc/topstories/v2/home.json?api-key=HiddenApiKeyJustForThisMessage")
Observable<NewsItemObject> getResults();
NewsItemObject is the Class that wraps NewsItem
In your ApiServices interface you expect that getResults() returns Observable<List<NewsItem>>. Based on JSON you getting back this is not gonna work, because your root JSON element is Object, not an Array.
You have to create new wrapper Class (ResultsWrapper) with "results" field type of List<NewsItem>. Your method in ApiServices interface will then be:
#GET("svc/topstories/v2/home.json?api-key=HiddenApiKeyJustForThisMessage")
Observable<ResultsWrapper> getResults();
That is what "Expected BEGIN_ARRAY but was BEGIN_OBJECT" says to you.
I'm struggling to implement a solution to retrieve multiple values from my api response ( https://www.thecocktaildb.com/api/json/v1/1/lookup.php?i=13060 ) and assign specific values to an array. Specifically values, strIngredient1, strIngredient2, strIngredient3 etc...
At present i created a POJO cocktail class as follows:
public class Cocktail implements Serializable {
#SerializedName("idDrink")
#Expose
private String idDrink;
#SerializedName("strDrink")
#Expose
private String strDrink;
#SerializedName("strVideo")
#Expose
private Object strVideo;
#SerializedName("strCategory")
#Expose
private String strCategory;
#SerializedName("strIBA")
#Expose
private Object strIBA;
#SerializedName("strAlcoholic")
#Expose
private String strAlcoholic;
#SerializedName("strGlass")
#Expose
private String strGlass;
#SerializedName("strInstructions")
#Expose
private String strInstructions;
#SerializedName("strDrinkThumb")
#Expose
private String strDrinkThumb;
#SerializedName("strIngredient1")
#Expose
private String strIngredient1;
#SerializedName("strIngredient2")
#Expose
private String strIngredient2;
#SerializedName("strIngredient3")
#Expose
private String strIngredient3;
#SerializedName("strIngredient4")
#Expose
private String strIngredient4;
#SerializedName("strIngredient5")
#Expose
private String strIngredient5;
#SerializedName("strIngredient6")
#Expose
private String strIngredient6;
#SerializedName("strIngredient7")
#Expose
private String strIngredient7;
#SerializedName("strIngredient8")
#Expose
private String strIngredient8;
#SerializedName("strIngredient9")
#Expose
private String strIngredient9;
#SerializedName("strIngredient10")
#Expose
private String strIngredient10;
#SerializedName("strIngredient11")
#Expose
private String strIngredient11;
#SerializedName("strIngredient12")
#Expose
private String strIngredient12;
#SerializedName("strIngredient13")
#Expose
private String strIngredient13;
#SerializedName("strIngredient14")
#Expose
private String strIngredient14;
#SerializedName("strIngredient15")
#Expose
private String strIngredient15;
#SerializedName("strMeasure1")
#Expose
private String strMeasure1;
#SerializedName("strMeasure2")
#Expose
private String strMeasure2;
#SerializedName("strMeasure3")
#Expose
private String strMeasure3;
#SerializedName("strMeasure4")
#Expose
private String strMeasure4;
#SerializedName("strMeasure5")
#Expose
private String strMeasure5;
#SerializedName("strMeasure6")
#Expose
private String strMeasure6;
#SerializedName("strMeasure7")
#Expose
private String strMeasure7;
#SerializedName("strMeasure8")
#Expose
private String strMeasure8;
#SerializedName("strMeasure9")
#Expose
private String strMeasure9;
#SerializedName("strMeasure10")
#Expose
private String strMeasure10;
#SerializedName("strMeasure11")
#Expose
private String strMeasure11;
#SerializedName("strMeasure12")
#Expose
private String strMeasure12;
#SerializedName("strMeasure13")
#Expose
private String strMeasure13;
#SerializedName("strMeasure14")
#Expose
private String strMeasure14;
#SerializedName("strMeasure15")
#Expose
private String strMeasure15;
#SerializedName("dateModified")
#Expose
private String dateModified;
public String getIdDrink() {
return idDrink;
}
public void setIdDrink(String idDrink) {
this.idDrink = idDrink;
}
public String getStrDrink() {
return strDrink;
}
public void setStrDrink(String strDrink) {
this.strDrink = strDrink;
}
public Object getStrVideo() {
return strVideo;
}
public void setStrVideo(Object strVideo) {
this.strVideo = strVideo;
}
public String getStrCategory() {
return strCategory;
}
public void setStrCategory(String strCategory) {
this.strCategory = strCategory;
}
public Object getStrIBA() {
return strIBA;
}
public void setStrIBA(Object strIBA) {
this.strIBA = strIBA;
}
public String getStrAlcoholic() {
return strAlcoholic;
}
public void setStrAlcoholic(String strAlcoholic) {
this.strAlcoholic = strAlcoholic;
}
public String getStrGlass() {
return strGlass;
}
public void setStrGlass(String strGlass) {
this.strGlass = strGlass;
}
public String getStrInstructions() {
return strInstructions;
}
public void setStrInstructions(String strInstructions) {
this.strInstructions = strInstructions;
}
public String getStrDrinkThumb() {
return strDrinkThumb;
}
public void setStrDrinkThumb(String strDrinkThumb) {
this.strDrinkThumb = strDrinkThumb;
}
public String getStrIngredient1() {
return strIngredient1;
}
public void setStrIngredient1(String strIngredient1) {
this.strIngredient1 = strIngredient1;
}
public String getStrIngredient2() {
return strIngredient2;
}
public void setStrIngredient2(String strIngredient2) {
this.strIngredient2 = strIngredient2;
}
public String getStrIngredient3() {
return strIngredient3;
}
public void setStrIngredient3(String strIngredient3) {
this.strIngredient3 = strIngredient3;
}
public String getStrIngredient4() {
return strIngredient4;
}
public void setStrIngredient4(String strIngredient4) {
this.strIngredient4 = strIngredient4;
}
public String getStrIngredient5() {
return strIngredient5;
}
public void setStrIngredient5(String strIngredient5) {
this.strIngredient5 = strIngredient5;
}
public String getStrIngredient6() {
return strIngredient6;
}
public void setStrIngredient6(String strIngredient6) {
this.strIngredient6 = strIngredient6;
}
public String getStrIngredient7() {
return strIngredient7;
}
public void setStrIngredient7(String strIngredient7) {
this.strIngredient7 = strIngredient7;
}
public String getStrIngredient8() {
return strIngredient8;
}
public void setStrIngredient8(String strIngredient8) {
this.strIngredient8 = strIngredient8;
}
public String getStrIngredient9() {
return strIngredient9;
}
public void setStrIngredient9(String strIngredient9) {
this.strIngredient9 = strIngredient9;
}
public String getStrIngredient10() {
return strIngredient10;
}
public void setStrIngredient10(String strIngredient10) {
this.strIngredient10 = strIngredient10;
}
public String getStrIngredient11() {
return strIngredient11;
}
public void setStrIngredient11(String strIngredient11) {
this.strIngredient11 = strIngredient11;
}
public String getStrIngredient12() {
return strIngredient12;
}
public void setStrIngredient12(String strIngredient12) {
this.strIngredient12 = strIngredient12;
}
public String getStrIngredient13() {
return strIngredient13;
}
public void setStrIngredient13(String strIngredient13) {
this.strIngredient13 = strIngredient13;
}
public String getStrIngredient14() {
return strIngredient14;
}
public void setStrIngredient14(String strIngredient14) {
this.strIngredient14 = strIngredient14;
}
public String getStrIngredient15() {
return strIngredient15;
}
public void setStrIngredient15(String strIngredient15) {
this.strIngredient15 = strIngredient15;
}
public String getStrMeasure1() {
return strMeasure1;
}
public void setStrMeasure1(String strMeasure1) {
this.strMeasure1 = strMeasure1;
}
public String getStrMeasure2() {
return strMeasure2;
}
public void setStrMeasure2(String strMeasure2) {
this.strMeasure2 = strMeasure2;
}
public String getStrMeasure3() {
return strMeasure3;
}
public void setStrMeasure3(String strMeasure3) {
this.strMeasure3 = strMeasure3;
}
public String getStrMeasure4() {
return strMeasure4;
}
public void setStrMeasure4(String strMeasure4) {
this.strMeasure4 = strMeasure4;
}
public String getStrMeasure5() {
return strMeasure5;
}
public void setStrMeasure5(String strMeasure5) {
this.strMeasure5 = strMeasure5;
}
public String getStrMeasure6() {
return strMeasure6;
}
public void setStrMeasure6(String strMeasure6) {
this.strMeasure6 = strMeasure6;
}
public String getStrMeasure7() {
return strMeasure7;
}
public void setStrMeasure7(String strMeasure7) {
this.strMeasure7 = strMeasure7;
}
public String getStrMeasure8() {
return strMeasure8;
}
public void setStrMeasure8(String strMeasure8) {
this.strMeasure8 = strMeasure8;
}
public String getStrMeasure9() {
return strMeasure9;
}
public void setStrMeasure9(String strMeasure9) {
this.strMeasure9 = strMeasure9;
}
public String getStrMeasure10() {
return strMeasure10;
}
public void setStrMeasure10(String strMeasure10) {
this.strMeasure10 = strMeasure10;
}
public String getStrMeasure11() {
return strMeasure11;
}
public void setStrMeasure11(String strMeasure11) {
this.strMeasure11 = strMeasure11;
}
public String getStrMeasure12() {
return strMeasure12;
}
public void setStrMeasure12(String strMeasure12) {
this.strMeasure12 = strMeasure12;
}
public String getStrMeasure13() {
return strMeasure13;
}
public void setStrMeasure13(String strMeasure13) {
this.strMeasure13 = strMeasure13;
}
public String getStrMeasure14() {
return strMeasure14;
}
public void setStrMeasure14(String strMeasure14) {
this.strMeasure14 = strMeasure14;
}
public String getStrMeasure15() {
return strMeasure15;
}
public void setStrMeasure15(String strMeasure15) {
this.strMeasure15 = strMeasure15;
}
public String getDateModified() {
return dateModified;
}
public void setDateModified(String dateModified) {
this.dateModified = dateModified;
}
And my API call is as follows:
#Override
protected Cocktail doInBackground(Cocktail... cocktails) {
Call<Cocktails> call = mApiService.getCocktail(id);
try {
Response<Cocktails> response = call.execute();
this.cocktails = response.body();
this.cocktail = this.cocktails.getCocktail().get(0);
Log.i(TAG, "Success: " + response.body().toString());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e);
e.printStackTrace();
} catch (IllegalStateException e) {
Log.e(TAG, "IllegalStateException: " + e);
e.printStackTrace();
}
return cocktail;
}
I know enough to realise that a large number of variables, ingredients and measures (many of which are empty) is the wrong approach but i'm struggling to find a solution with retrofit to create an array of these values. I've not found any way to assign multiple SerializedNames to a single array variable?
The option that jumps out at me is looping through the response pulling out the key values in onSuccess but this seems to go against the simplicity of using retrofit?
I starting out with RxJava and Retrofit and wanted to create a simple app to show a list of 100 cryptocurrencies.
I am making an api call which results in something like this :
{
"Response": "Success",
"Message": "Coin list succesfully returned!",
"BaseImageUrl": "https://www.cryptocompare.com",
"BaseLinkUrl": "https://www.cryptocompare.com",
"Data": {
"LTC": {
"Id": "3808",
"Url": "/coins/ltc/overview",
"ImageUrl": "/media/19782/ltc.png",
"Name": "LTC",
"CoinName": "Litecoin",
"FullName": "Litecoin (LTC)",
"Algorithm": "Scrypt",
"ProofType": "PoW",
"SortOrder": "2"
}
...
},
"Type": 100
}
But all I want from this is "Response" and "Data". Since it is not practical to create a 100 different model classes for each coin, I want to store information of all the coins in a common class named Coin which would look something like this :
public class Coins {
#SerializedName("Algorithm")
private String mAlgorithm;
#SerializedName("CoinName")
private String mCoinName;
#SerializedName("FullName")
private String mFullName;
#SerializedName("FullyPremined")
private String mFullyPremined;
#SerializedName("Id")
private String mId;
#SerializedName("ImageUrl")
private String mImageUrl;
#SerializedName("Name")
private String mName;
#SerializedName("PreMinedValue")
private String mPreMinedValue;
#SerializedName("ProofType")
private String mProofType;
#SerializedName("SortOrder")
private String mSortOrder;
#SerializedName("Sponsored")
private Boolean mSponsored;
#SerializedName("Symbol")
private String mSymbol;
#SerializedName("TotalCoinSupply")
private String mTotalCoinSupply;
#SerializedName("TotalCoinsFreeFloat")
private String mTotalCoinsFreeFloat;
#SerializedName("Url")
private String mUrl;
public String getAlgorithm() {
return mAlgorithm;
}
public void setAlgorithm(String Algorithm) {
mAlgorithm = Algorithm;
}
public String getCoinName() {
return mCoinName;
}
public void setCoinName(String CoinName) {
mCoinName = CoinName;
}
public String getFullName() {
return mFullName;
}
public void setFullName(String FullName) {
mFullName = FullName;
}
public String getFullyPremined() {
return mFullyPremined;
}
public void setFullyPremined(String FullyPremined) {
mFullyPremined = FullyPremined;
}
public String getId() {
return mId;
}
public void setId(String Id) {
mId = Id;
}
public String getImageUrl() {
return mImageUrl;
}
public void setImageUrl(String ImageUrl) {
mImageUrl = ImageUrl;
}
public String getName() {
return mName;
}
public void setName(String Name) {
mName = Name;
}
public String getPreMinedValue() {
return mPreMinedValue;
}
public void setPreMinedValue(String PreMinedValue) {
mPreMinedValue = PreMinedValue;
}
public String getProofType() {
return mProofType;
}
public void setProofType(String ProofType) {
mProofType = ProofType;
}
public String getSortOrder() {
return mSortOrder;
}
public void setSortOrder(String SortOrder) {
mSortOrder = SortOrder;
}
public Boolean getSponsored() {
return mSponsored;
}
public void setSponsored(Boolean Sponsored) {
mSponsored = Sponsored;
}
public String getSymbol() {
return mSymbol;
}
public void setSymbol(String Symbol) {
mSymbol = Symbol;
}
public String getTotalCoinSupply() {
return mTotalCoinSupply;
}
public void setTotalCoinSupply(String TotalCoinSupply) {
mTotalCoinSupply = TotalCoinSupply;
}
public String getTotalCoinsFreeFloat() {
return mTotalCoinsFreeFloat;
}
public void setTotalCoinsFreeFloat(String TotalCoinsFreeFloat) {
mTotalCoinsFreeFloat = TotalCoinsFreeFloat;
}
public String getUrl() {
return mUrl;
}
public void setUrl(String Url) {
mUrl = Url;
}
}
So finally my mapped response class would look like :
public class CoinsListResponse {
private boolean success;
private List<Coins> coinsList;
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public List<Coins> getCoinsList() {
return coinsList;
}
public void setCoinsList(List<Coins> coinsList) {
this.coinsList = coinsList;
}
}
I haven't added #Serialized notations because I don't know what key to annotate it with.
My Retrofit service interface has a method to return the results to this map :
public interface CoinService {
#NonNull
#POST
Observable<CoinsListResponse> getCoinList();
}
Since, I am a starter with Retrofit and RxAndroid, there might be a better method to do this, which I am not aware of. If so, please mention that as well !! I am trying to get my head around this for days but couldn't find any answer on SO as well.
Please Help !!
Change
private List<Coins> coinsList;
to
#SerializedName("Data")
private Map<String, Coins> coinsByName;
You can then either just use coinsByName.values() or call e.g. coinsByName.get("LTC")
I am trying to load this test json string into an object using Gson but every element carries null. There is no exception triggered during the conversion. Please let me know what I might be doing wrong.
Appreciate your help.
I am writing a longer comment here only because it is throwing an error for not writing enough text to ask my query. I can't imagine why it would do such checks.
String testSeg1 = "{\"FlightSegment\":{\"discount\":0,\"childTaxBreakup\":\"0,0,0\",\"adultTaxBreakup\":\"0,154,413\",\"viaFlight\":\"\",\"airportTaxInfant\":0,\"OperatingAirlineFlightNumber\":144,\"StopQuantity\":0,\"BookingClass\":{\"Availability\":9,\"ResBookDesigCode\":\"S\"},\"AirEquipType\":\"77W\",\"RPH\":\"\",\"airportTax\":567,\"airportTaxChild\":0,\"OperatingAirlineCode\":\"AI\",\"DepartureDateTime\":\"2017-11-27T17:00:00\",\"ArrivalDateTime\":\"2017-11-27T19:10:00\",\"imageFileName\":\"http://live.arzoo.com/FlightWS/image/AirIndia.gif\",\"FlightNumber\":144,\"airLineName\":\"Air India\",\"DepartureAirportCode\":\"BOM\",\"octax\":0,\"ArrivalAirportCode\":\"DEL\",\"BookingClassFare\":{\"bookingclass\":\"S\",\"adultFare\":3955,\"commissionOnTCharge\":0,\"farebasiscode\":\"glW5J3cLgtM=\",\"Rule\":\"This fare is Non Refundable <br> Baggage : 25K<br>Booking Class : S|Re-Schedule Charges: Rs. 750 per sector + Fare difference (If any) +admin fee 500 + Service Fee of Rs. 250 Sector .|Cancellation Charges : Basic fare +Airline administration fee 500 + Service Charges 250 Per Passenger Per Sector .\\t\\t\\t\\t\\t |\",\"adultCommission\":0,\"childCommission\":0,\"classType\":\"Economy\"},\"infantTaxBreakup\":\"0,0,0\"}}";
Type testlistType = new TypeToken<FlightSegment>(){}.getType();
FlightSegment testFlt = gson.fromJson(testSeg1, testlistType);
public class FlightSegment {
#SerializedName("Discount")
#Expose
private String discount;
#SerializedName("AirEquipType")
#Expose
private String airEquipType;
#SerializedName("ArrivalAirportCode")
#Expose
private String arrivalAirportCode;
#SerializedName("ArrivalDateTime")
#Expose
private String arrivalDateTime;
#SerializedName("DepartureAirportCode")
#Expose
private String departureAirportCode;
#SerializedName("DepartureDateTime")
#Expose
private String departureDateTime;
#SerializedName("FlightNumber")
#Expose
private String flightNumber;
#SerializedName("OperatingAirlineCode")
#Expose
private String operatingAirlineCode;
#SerializedName("OperatingAirlineFlightNumber")
#Expose
private String operatingAirlineFlightNumber;
#SerializedName("RPH")
#Expose
private String rPH;
#SerializedName("StopQuantity")
#Expose
private String stopQuantity;
#SerializedName("airLineName")
#Expose
private String airLineName;
#SerializedName("airportTax")
#Expose
private String airportTax;
#SerializedName("imageFileName")
#Expose
private String imageFileName;
#SerializedName("viaFlight")
#Expose
private String viaFlight;
#SerializedName("airportTaxChild")
#Expose
private String airportTaxChild;
#SerializedName("airportTaxInfant")
#Expose
private String airportTaxInfant;
#SerializedName("adultTaxBreakup")
#Expose
private String adultTaxBreakup;
#SerializedName("childTaxBreakup")
#Expose
private String childTaxBreakup;
#SerializedName("infantTaxBreakup")
#Expose
private String infantTaxBreakup;
#SerializedName("octax")
#Expose
private String octax;
#SerializedName("BookingClass")
#Expose
private BookingClass bookingClass;
#SerializedName("BookingClassFare")
#Expose
private BookingClassFare bookingClassFare;
public String getAirEquipType() {
return airEquipType;
}
public void setAirEquipType(String airEquipType) {
this.airEquipType = airEquipType;
}
public String getArrivalAirportCode() {
return arrivalAirportCode;
}
public void setArrivalAirportCode(String arrivalAirportCode) {
this.arrivalAirportCode = arrivalAirportCode;
}
public String getArrivalDateTime() {
return arrivalDateTime;
}
public void setArrivalDateTime(String arrivalDateTime) {
this.arrivalDateTime = arrivalDateTime;
}
public String getDepartureAirportCode() {
return departureAirportCode;
}
public void setDepartureAirportCode(String departureAirportCode) {
this.departureAirportCode = departureAirportCode;
}
public String getDepartureDateTime() {
return departureDateTime;
}
public void setDepartureDateTime(String departureDateTime) {
this.departureDateTime = departureDateTime;
}
public String getFlightNumber() {
return flightNumber;
}
public void setFlightNumber(String flightNumber) {
this.flightNumber = flightNumber;
}
public String getOperatingAirlineCode() {
return operatingAirlineCode;
}
public void setOperatingAirlineCode(String operatingAirlineCode) {
this.operatingAirlineCode = operatingAirlineCode;
}
public String getOperatingAirlineFlightNumber() {
return operatingAirlineFlightNumber;
}
public void setOperatingAirlineFlightNumber(String operatingAirlineFlightNumber) {
this.operatingAirlineFlightNumber = operatingAirlineFlightNumber;
}
public String getRPH() {
return rPH;
}
public void setRPH(String rPH) {
this.rPH = rPH;
}
public String getStopQuantity() {
return stopQuantity;
}
public void setStopQuantity(String stopQuantity) {
this.stopQuantity = stopQuantity;
}
public String getAirLineName() {
return airLineName;
}
public void setAirLineName(String airLineName) {
this.airLineName = airLineName;
}
public String getAirportTax() {
return airportTax;
}
public void setAirportTax(String airportTax) {
this.airportTax = airportTax;
}
public String getImageFileName() {
return imageFileName;
}
public void setImageFileName(String imageFileName) {
this.imageFileName = imageFileName;
}
public String getViaFlight() {
return viaFlight;
}
public void setViaFlight(String viaFlight) {
this.viaFlight = viaFlight;
}
public BookingClass getBookingClass() {
return bookingClass;
}
public void setBookingClass(BookingClass bookingClass) {
this.bookingClass = bookingClass;
}
public BookingClassFare getBookingClassFare() {
return bookingClassFare;
}
public void setBookingClassFare(BookingClassFare bookingClassFare) {
this.bookingClassFare = bookingClassFare;
}
public String getDiscount() {
return discount;
}
public void setDiscount(String discount) {
this.discount = discount;
}
public String getAirportTaxChild() {
return airportTaxChild;
}
public void setAirportTaxChild(String airportTaxChild) {
this.airportTaxChild = airportTaxChild;
}
public String getAirportTaxInfant() {
return airportTaxInfant;
}
public void setAirportTaxInfant(String airportTaxInfant) {
this.airportTaxInfant = airportTaxInfant;
}
public String getAdultTaxBreakup() {
return adultTaxBreakup;
}
public void setAdultTaxBreakup(String adultTaxBreakup) {
this.adultTaxBreakup = adultTaxBreakup;
}
public String getChildTaxBreakup() {
return childTaxBreakup;
}
public void setChildTaxBreakup(String childTaxBreakup) {
this.childTaxBreakup = childTaxBreakup;
}
public String getInfantTaxBreakup() {
return infantTaxBreakup;
}
public void setInfantTaxBreakup(String infantTaxBreakup) {
this.infantTaxBreakup = infantTaxBreakup;
}
public String getOctax() {
return octax;
}
public void setOctax(String octax) {
this.octax = octax;
}
}
This is the JSON String -
{"FlightSegment":{"discount":0,"childTaxBreakup":"0,0,0","adultTaxBreakup":"0,154,413","viaFlight":"","airportTaxInfant":0,"OperatingAirlineFlightNumber":144,"StopQuantity":0,"BookingClass":{"Availability":9,"ResBookDesigCode":"S"},"AirEquipType":"77W","RPH":"","airportTax":567,"airportTaxChild":0,"OperatingAirlineCode":"AI","DepartureDateTime":"2017-11-27T17:00:00","ArrivalDateTime":"2017-11-27T19:10:00","imageFileName":"http://live.arzoo.com/FlightWS/image/AirIndia.gif","FlightNumber":144,"airLineName":"Air India","DepartureAirportCode":"BOM","octax":0,"ArrivalAirportCode":"DEL","BookingClassFare":{"bookingclass":"S","adultFare":3955,"commissionOnTCharge":0,"farebasiscode":"glW5J3cLgtM=","Rule":"This fare is Non Refundable <br> Baggage : 25K<br>Booking Class : S|Re-Schedule Charges: Rs. 750 per sector + Fare difference (If any) +admin fee 500 + Service Fee of Rs. 250 Sector .|Cancellation Charges : Basic fare +Airline administration fee 500 + Service Charges 250 Per Passenger Per Sector .ttttt |","adultCommission":0,"childCommission":0,"classType":"Economy"},"infantTaxBreakup":"0,0,0"}}
Don't use TypeToken because your are not loading a List of Objects, use the class directly :
FlightSegment testFlt = gson.fromJson(testSeg1, FlightSegment.class);
I'm trying to store a coordnates (array of double) using Realm-java,but I'm not able to do it.
Here is an example of json that I'm trying to parse:
{"_id":"597cd98b3af0b6315576d717",
"comarca":"string",
"font":null,
"imatge":"string",
"location":{
"coordinates":[41.64642,1.1393],
"type":"Point"
},
"marca":"string",
"municipi":"string",
"publisher":"string",
"recursurl":"string",
"tematica":"string",
"titol":"string"
}
My global object code is like that
public class Images extends RealmObject implements Serializable {
#PrimaryKey
private String _id;
private String recursurl;
private String titol;
private String municipi;
private String comarca;
private String marca;
private String imatge;
#Nullable
private Location location;
private String tematica;
private String font;
private String parentRoute;
public Location getLocation() {return location;}
public void setLocation(Location location) {this.location = location;}
public String getParentRoute() {
return parentRoute;
}
public void setParentRoute(String parentRoute) {
this.parentRoute = parentRoute;
}
public String get_id() {
return _id;
}
public void set_id(String _id) {
this._id = _id;
}
public String getFont() {
return font;
}
public void setFont(String font) {
this.font = font;
}
public String getRecursurl() {
return recursurl;
}
public void setRecursurl(String recursurl) {
this.recursurl = recursurl;
}
public String getTitol() {
return titol;
}
public void setTitol(String titol) {
this.titol = titol;
}
public String getMunicipi() {
return municipi;
}
public void setMunicipi(String municipi) {
this.municipi = municipi;
}
public String getComarca() {
return comarca;
}
public void setComarca(String comarca) {
this.comarca = comarca;
}
public String getMarca() {
return marca;
}
public void setMarca(String marca) {
this.marca = marca;
}
public String getImatge() {
return imatge;
}
public void setImatge(String imatge) {
this.imatge = imatge;
}
public String getTematica() {
return tematica;
}
public void setTematica(String tematica) {
this.tematica = tematica;
}
And Location is a composite of type and a realmlist
Location.java
public class Location extends RealmObject implements Serializable {
private String type;
private RealmList<RealmDoubleObject> coordinates;
public Location() {
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public RealmList<RealmDoubleObject> getCoordinates() {
return coordinates;
}
public void setCoordinates(RealmList<RealmDoubleObject> coordinates) {
this.coordinates = coordinates;
}
}
RealmDoubleObject.java
public class RealmDoubleObject extends RealmObject implements Serializable{
private Double value;
public RealmDoubleObject() {
}
public Double getDoublevalue() {
return value;
}
public void setDoublevalue(Double value) {
this.value = value;
}
}
The error is com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was NUMBER at path $[0].location.coordinates[0] but I'm not able to figure out why this number is not "fitting" by RealmDoubleObject.
For those that not familiar with realm RealmList doesn't work and you have to build your own realm object.
Thank you. I hope to find some Realm experts here!
SOLVED:
using Gson deserializer it can be done
First we have to initialize the gson object like this
Gson gson = new GsonBuilder()
.setExclusionStrategies(new ExclusionStrategy() {
#Override
public boolean shouldSkipField(FieldAttributes f) {
return f.getDeclaringClass().equals(RealmObject.class);
}
#Override
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}
})
.registerTypeAdapter(new TypeToken<RealmList<RealmDoubleObject>>() {}.getType(), new TypeAdapter<RealmList<RealmDoubleObject>>() {
#Override
public void write(JsonWriter out, RealmList<RealmDoubleObject> value) throws IOException {
// Ignore
}
#Override
public RealmList<RealmDoubleObject> read(JsonReader in) throws IOException {
RealmList<RealmDoubleObject> list = new RealmList<RealmDoubleObject>();
in.beginArray();
while (in.hasNext()) {
Double valor = in.nextDouble();
list.add(new RealmDoubleObject(valor));
}
in.endArray();
return list;
}
})
.create();
And then we have to put some other constructor method
public RealmDoubleObject(double v) {
this.value = v;
}
and this is all.
Thanks for the help #EpicPandaForce