Storing JSON object using Volley - java

This is the structure of the JSON I need to Load,
{
"readme_0" : "THIS JSON IS THE RESULT OF YOUR SEARCH QUERY - THERE IS NO WEB PAGE WHICH SHOWS THE RESULT!",
"readme_1" : "loklak.org is the framework for a message search system, not the portal, read: http://loklak.org/about.html#notasearchportal",
"readme_2" : "This is supposed to be the back-end of a search portal. For the api, see http://loklak.org/api.html",
"readme_3" : "Parameters q=(query), source=(cache|backend|twitter|all), callback=p for jsonp, maximumRecords=(message count), minified=(true|false)",
"search_metadata" : {
"itemsPerPage" : "100",
"count" : "100",
"count_twitter_all" : 0,
"count_twitter_new" : 100,
"count_backend" : 0,
"count_cache" : 78780,
"hits" : 78780,
"period" : 3066,
"query" : "apple",
"client" : "180.215.121.78",
"time" : 5219,
"servicereduction" : "false",
"scraperInfo" : "http://45.55.245.191:9000,local"
},
"statuses" : [ {
"created_at" : "2016-01-09T12:11:38.000Z",
"screen_name" : "arifazmi92",
"text" : "Perhaps I shouldn't have eaten that pisang goreng cheese perisa green apple. <img class=\"Emoji Emoji--forText\" src=\"https://abs.twimg.com/emoji/v2/72x72/1f605.png\" draggable=\"false\" alt=\"😅\" title=\"Smiling face with open mouth and cold sweat\" aria-label=\"Emoji: Smiling face with open mouth and cold sweat\"><img class=\"Emoji Emoji--forText\" src=\"https://abs.twimg.com/emoji/v2/72x72/1f605.png\" draggable=\"false\" alt=\"😅\" title=\"Smiling face with open mouth and cold sweat\" aria-label=\"Emoji: Smiling face with open mouth and cold sweat\"><img class=\"Emoji Emoji--forText\" src=\"https://abs.twimg.com/emoji/v2/72x72/1f605.png\" draggable=\"false\" alt=\"😅\" title=\"Smiling face with open mouth and cold sweat\" aria-label=\"Emoji: Smiling face with open mouth and cold sweat\">",
"link" : "https://twitter.com/arifazmi92/status/685796067082813440",
"id_str" : "685796067082813440",
"source_type" : "TWITTER",
"provider_type" : "SCRAPED",
"retweet_count" : 0,
"favourites_count" : 0,
"images" : [ ],
"images_count" : 0,
"audio" : [ ],
"audio_count" : 0,
"videos" : [ ],
"videos_count" : 0,
"place_name" : "Bandar Shah Alam, Selangor",
"place_id" : "9be3b0eca6c21f6c",
"place_context" : "FROM",
"place_country" : "Malaysia",
"place_country_code" : "MY",
"place_country_center" : [ -59.30559537806809, 3.4418498787292435 ],
"location_point" : [ 101.53280621465888, 3.0850698533863863 ],
"location_radius" : 0,
"location_mark" : [ 101.52542227271437, 3.0911033774188725 ],
"location_source" : "PLACE",
"hosts" : [ "abs.twimg.com" ],
"hosts_count" : 1,
"links" : [ "https://abs.twimg.com/emoji/v2/72x72/1f605.png\"", "https://abs.twimg.com/emoji/v2/72x72/1f605.png\"", "https://abs.twimg.com/emoji/v2/72x72/1f605.png\"" ],
"links_count" : 3,
"mentions" : [ ],
"mentions_count" : 0,
"hashtags" : [ ],
"hashtags_count" : 0,
"without_l_len" : 626,
"without_lu_len" : 626,
"without_luh_len" : 626,
"user" : {
"screen_name" : "arifazmi92",
"user_id" : "44503967",
"name" : "Arif Azmi",
"profile_image_url_https" : "https://pbs.twimg.com/profile_images/685788990004301824/NbFnnLuO_bigger.jpg",
"appearance_first" : "2016-01-09T12:11:57.933Z",
"appearance_latest" : "2016-01-09T12:11:57.933Z"
}
}
} ],
"aggregations" : { }
}
And these are my POJO classes that I've generated:
MainPojo.class
public class MainPojo
{
#SerializedName("readme_0")
#Expose
private String readme0;
#SerializedName("readme_1")
#Expose
private String readme1;
#SerializedName("readme_2")
#Expose
private String readme2;
#SerializedName("readme_3")
#Expose
private String readme3;
#SerializedName("search_metadata")
#Expose
private SearchMetadata searchMetadata;
#SerializedName("statuses")
#Expose
private List<Status> statuses = new ArrayList<Status>();
#SerializedName("aggregations")
#Expose
private Aggregations aggregations;
public String getReadme0() {
return readme0;
}
public void setReadme0(String readme0) {
this.readme0 = readme0;
}
public String getReadme1() {
return readme1;
}
public void setReadme1(String readme1) {
this.readme1 = readme1;
}
public String getReadme2() {
return readme2;
}
public void setReadme2(String readme2) {
this.readme2 = readme2;
}
public String getReadme3() {
return readme3;
}
public void setReadme3(String readme3) {
this.readme3 = readme3;
}
public SearchMetadata getSearchMetadata() {
return searchMetadata;
}
public void setSearchMetadata(SearchMetadata searchMetadata) {
this.searchMetadata = searchMetadata;
}
public List<Status> getStatuses() {
return statuses;
}
public void setStatuses(List<Status> statuses) {
this.statuses = statuses;
}
public Aggregations getAggregations() {
return aggregations;
}
public void setAggregations(Aggregations aggregations) {
this.aggregations = aggregations;
}
}
Status.class
public class Status
{
#SerializedName("created_at")
#Expose
private String createdAt;
#SerializedName("screen_name")
#Expose
private String screenName;
#SerializedName("text")
#Expose
private String text;
#SerializedName("link")
#Expose
private String link;
#SerializedName("id_str")
#Expose
private String idStr;
#SerializedName("source_type")
#Expose
private String sourceType;
#SerializedName("provider_type")
#Expose
private String providerType;
#SerializedName("retweet_count")
#Expose
private Integer retweetCount;
#SerializedName("favourites_count")
#Expose
private Integer favouritesCount;
#SerializedName("images")
#Expose
private List<Object> images = new ArrayList<Object>();
#SerializedName("images_count")
#Expose
private Integer imagesCount;
#SerializedName("audio")
#Expose
private List<Object> audio = new ArrayList<Object>();
#SerializedName("audio_count")
#Expose
private Integer audioCount;
#SerializedName("videos")
#Expose
private List<Object> videos = new ArrayList<Object>();
#SerializedName("videos_count")
#Expose
private Integer videosCount;
#SerializedName("place_name")
#Expose
private String placeName;
#SerializedName("place_id")
#Expose
private String placeId;
#SerializedName("place_context")
#Expose
private String placeContext;
#SerializedName("location_point")
#Expose
private List<Double> locationPoint = new ArrayList<Double>();
#SerializedName("location_radius")
#Expose
private Integer locationRadius;
#SerializedName("location_mark")
#Expose
private List<Double> locationMark = new ArrayList<Double>();
#SerializedName("location_source")
#Expose
private String locationSource;
#SerializedName("hosts")
#Expose
private List<String> hosts = new ArrayList<String>();
#SerializedName("hosts_count")
#Expose
private Integer hostsCount;
#SerializedName("links")
#Expose
private List<String> links = new ArrayList<String>();
#SerializedName("links_count")
#Expose
private Integer linksCount;
#SerializedName("mentions")
#Expose
private List<Object> mentions = new ArrayList<Object>();
#SerializedName("mentions_count")
#Expose
private Integer mentionsCount;
#SerializedName("hashtags")
#Expose
private List<Object> hashtags = new ArrayList<Object>();
#SerializedName("hashtags_count")
#Expose
private Integer hashtagsCount;
#SerializedName("without_l_len")
#Expose
private Integer withoutLLen;
#SerializedName("without_lu_len")
#Expose
private Integer withoutLuLen;
#SerializedName("without_luh_len")
#Expose
private Integer withoutLuhLen;
#SerializedName("user")
#Expose
private User user;
#SerializedName("provider_hash")
#Expose
private String providerHash;
#SerializedName("classifier_language")
#Expose
private String classifierLanguage;
#SerializedName("classifier_language_probability")
#Expose
private Double classifierLanguageProbability;
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public String getScreenName() {
return screenName;
}
public void setScreenName(String screenName) {
this.screenName = screenName;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getIdStr() {
return idStr;
}
public void setIdStr(String idStr) {
this.idStr = idStr;
}
public String getSourceType() {
return sourceType;
}
public void setSourceType(String sourceType) {
this.sourceType = sourceType;
}
public String getProviderType() {
return providerType;
}
public void setProviderType(String providerType) {
this.providerType = providerType;
}
public Integer getRetweetCount() {
return retweetCount;
}
public void setRetweetCount(Integer retweetCount) {
this.retweetCount = retweetCount;
}
public Integer getFavouritesCount() {
return favouritesCount;
}
public void setFavouritesCount(Integer favouritesCount) {
this.favouritesCount = favouritesCount;
}
public List<Object> getImages() {
return images;
}
public void setImages(List<Object> images) {
this.images = images;
}
public Integer getImagesCount() {
return imagesCount;
}
public void setImagesCount(Integer imagesCount) {
this.imagesCount = imagesCount;
}
public List<Object> getAudio() {
return audio;
}
public void setAudio(List<Object> audio) {
this.audio = audio;
}
public Integer getAudioCount() {
return audioCount;
}
public void setAudioCount(Integer audioCount) {
this.audioCount = audioCount;
}
public List<Object> getVideos() {
return videos;
}
public void setVideos(List<Object> videos) {
this.videos = videos;
}
public Integer getVideosCount() {
return videosCount;
}
public void setVideosCount(Integer videosCount) {
this.videosCount = videosCount;
}
public String getPlaceName() {
return placeName;
}
public void setPlaceName(String placeName) {
this.placeName = placeName;
}
public String getPlaceId() {
return placeId;
}
public void setPlaceId(String placeId) {
this.placeId = placeId;
}
public String getPlaceContext() {
return placeContext;
}
public void setPlaceContext(String placeContext) {
this.placeContext = placeContext;
}
public List<Double> getLocationPoint() {
return locationPoint;
}
public void setLocationPoint(List<Double> locationPoint) {
this.locationPoint = locationPoint;
}
public Integer getLocationRadius() {
return locationRadius;
}
public void setLocationRadius(Integer locationRadius) {
this.locationRadius = locationRadius;
}
public List<Double> getLocationMark() {
return locationMark;
}
public void setLocationMark(List<Double> locationMark) {
this.locationMark = locationMark;
}
public String getLocationSource() {
return locationSource;
}
public void setLocationSource(String locationSource) {
this.locationSource = locationSource;
}
public List<String> getHosts() {
return hosts;
}
public void setHosts(List<String> hosts) {
this.hosts = hosts;
}
public Integer getHostsCount() {
return hostsCount;
}
public void setHostsCount(Integer hostsCount) {
this.hostsCount = hostsCount;
}
public List<String> getLinks() {
return links;
}
public void setLinks(List<String> links) {
this.links = links;
}
public Integer getLinksCount() {
return linksCount;
}
public void setLinksCount(Integer linksCount) {
this.linksCount = linksCount;
}
public List<Object> getMentions() {
return mentions;
}
public void setMentions(List<Object> mentions) {
this.mentions = mentions;
}
public Integer getMentionsCount() {
return mentionsCount;
}
public void setMentionsCount(Integer mentionsCount) {
this.mentionsCount = mentionsCount;
}
public List<Object> getHashtags() {
return hashtags;
}
public void setHashtags(List<Object> hashtags) {
this.hashtags = hashtags;
}
public Integer getHashtagsCount() {
return hashtagsCount;
}
public void setHashtagsCount(Integer hashtagsCount) {
this.hashtagsCount = hashtagsCount;
}
public Integer getWithoutLLen() {
return withoutLLen;
}
public void setWithoutLLen(Integer withoutLLen) {
this.withoutLLen = withoutLLen;
}
public Integer getWithoutLuLen() {
return withoutLuLen;
}
public void setWithoutLuLen(Integer withoutLuLen) {
this.withoutLuLen = withoutLuLen;
}
public Integer getWithoutLuhLen() {
return withoutLuhLen;
}
public void setWithoutLuhLen(Integer withoutLuhLen) {
this.withoutLuhLen = withoutLuhLen;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getProviderHash() {
return providerHash;
}
public void setProviderHash(String providerHash) {
this.providerHash = providerHash;
}
public String getClassifierLanguage() {
return classifierLanguage;
}
public void setClassifierLanguage(String classifierLanguage) {
this.classifierLanguage = classifierLanguage;
}
public Double getClassifierLanguageProbability() {
return classifierLanguageProbability;
}
public void setClassifierLanguageProbability(Double classifierLanguageProbability) {
this.classifierLanguageProbability = classifierLanguageProbability;
}
}
User.java
public class User {
#SerializedName("screen_name")
#Expose
private String screenName;
#SerializedName("user_id")
#Expose
private String userId;
#SerializedName("name")
#Expose
private String name;
#SerializedName("profile_image_url_https")
#Expose
private String profileImageUrlHttps;
#SerializedName("appearance_first")
#Expose
private String appearanceFirst;
#SerializedName("appearance_latest")
#Expose
private String appearanceLatest;
public String getScreenName() {
return screenName;
}
public void setScreenName(String screenName) {
this.screenName = screenName;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getProfileImageUrlHttps() {
return profileImageUrlHttps;
}
public void setProfileImageUrlHttps(String profileImageUrlHttps) {
this.profileImageUrlHttps = profileImageUrlHttps;
}
public String getAppearanceFirst() {
return appearanceFirst;
}
public void setAppearanceFirst(String appearanceFirst) {
this.appearanceFirst = appearanceFirst;
}
public String getAppearanceLatest() {
return appearanceLatest;
}
public void setAppearanceLatest(String appearanceLatest) {
this.appearanceLatest = appearanceLatest;
}
}
Aggregations.class
public class Aggregations {
}
And finally, this is the code I use to read the JSON and store as JSON objects,
SharedPreferences Tempx = getSharedPreferences("ActivitySession", Context.MODE_PRIVATE);
SharedPreferences.Editor edx = Tempx.edit();
edx.putString("GSON_FEED", response.toString());
edx.apply();
Gson gson = new Gson();
JsonParser parser = new JsonParser();
try{
JsonArray jArray = parser.parse(Tempx.getString("GSON_FEED","")).getAsJsonArray();
for(JsonElement obj : jArray )
{
MainPojo cse = gson.fromJson( obj , MainPojo.class);
TweetList.add(cse);
}
}catch(Throwable e) {
JsonElement obj = parser.parse(Tempx.getString("GSON_FEED","")).getAsJsonObject();
MainPojo cse = gson.fromJson( obj , MainPojo.class);
TweetList.add(cse);
}
Though I am able to log the JSON as String, I don't know if I am storing it the wrong way, any help will be much appreciated, Thanks!

You could define a custom deserializer and register a type adapter with GSON. Also
why are you using this:
JsonArray jArray = parser.parse(Tempx.getString("GSON_FEED","")).getAsJsonArray();
.. when you intend to use GSON for deserialization? You could just do it in your deserializer.
https://sites.google.com/site/gson/gson-user-guide#TOC-Custom-Serialization-and-Deserialization
EG:
public class FooDeserializer implements JsonDeserializer<Foos>
{
#Override public Foos deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
{
JsonObject jsonObject = json.getAsJsonObject();
JsonArray statusArray = jsonObject.get("statuses").getAsJsonArray();
Foos result = new Foos();
ArrayList fooArray = new ArrayList<>;
for (JsonElement e : statusArray) {
fooArray.add(new Foo());
}
result.setFoos(fooArray);
return result;
}
}

Related

When retrieving json array from empty sharedpreference, java.lang.String cannot be converted to JSONObject exception comes

W/System.err: org.json.JSONException: Value Responsemodel$Banner#b494bac at 0 of type java.lang.String cannot be converted to JSONObject
output:
[Responsemodel$Banner#e5af3c3, Responsemodel$Banner#ed16440, Responsemodel$Banner#5335f79, Responsemodel$Banner#e8cb4be, Responsemodel$Banner#9ef091f]
Getting from SharedPreferences
String getbanner = preferences.getString(Constants.banner_list, null);
Log.i("banner_str", getbanner);
if (getbanner != null) {
JSONArray jsonArray2 = new JSONArray(getbanner);
Log.i("Sharedpref1", jsonArray2.toString());
if (banner_list != null) {
banner_list.clear();
Log.i("Sharedpref2", jsonArray2.toString());
for (int x = 0; x < jsonArray2.length(); x++) {
String object = jsonArray2.getJSONObject(x).getString("imgUrl");
Log.i("bid", object);
HashMap<String, String> map = new HashMap<>();
map.put("imgUrl", object);
banner_list.add(map);
}
}
}
} catch (NullPointerException | JSONException e1) {
e1.printStackTrace();
}
Banner_adapter adapter1 = new Banner_adapter(banner_list);
snapHelper.attachToRecyclerView(recyclerView);
recyclerView.setAdapter(adapter1);
adapter1.notifyDataSetChanged();
Saved in SharedPreferences
getbalres_dto model = response.body(); SharedPreferences.Editor editor = preferences.edit();
editor.putString(Constants.currentBalance, model.getMOBILEAPPLICATION().getCurrentBalance())
.putString(Constants.outletName, model.getMOBILEAPPLICATION().getOutletName())
.putString(Constants.name, model.getMOBILEAPPLICATION().getName())
.putString(Constants.news, model.getMOBILEAPPLICATION().getNews())
.putString(Constants.banner_list, model.getMOBILEAPPLICATION().getBanner().toString())
.putString(Constants.instaurl, model.getMOBILEAPPLICATION().getInstagramUrl())
.putString(Constants.fburl, model.getMOBILEAPPLICATION().getFacebookUrl())
.putString(Constants.youtubeurl, model.getMOBILEAPPLICATION().getYoutubeUrl())
.putString(Constants.twitterurl, model.getMOBILEAPPLICATION().getTwitterUrl())
.putString(Constants.aepsBalance, model.getMOBILEAPPLICATION().getAepsBalance())
.putString(Constants.cartItem, model.getMOBILEAPPLICATION().getCartItem())
.commit();
Java PoJO class
public class getbalres_dto {
#SerializedName("MOBILE_APPLICATION")
#Expose
private MOBILEAPPLICATION mOBILEAPPLICATION;
public MOBILEAPPLICATION getMOBILEAPPLICATION() {
return mOBILEAPPLICATION;
}
public void setMOBILEAPPLICATION(MOBILEAPPLICATION mOBILEAPPLICATION) {
this.mOBILEAPPLICATION = mOBILEAPPLICATION;
}
public class MOBILEAPPLICATION {
#SerializedName("response")
#Expose
private String response;
#SerializedName("Message")
#Expose
private String message;
#SerializedName("news")
#Expose
private String news;
#SerializedName("banner")
#Expose
private JsonArray banner;
#SerializedName("name")
#Expose
private String name;
#SerializedName("outletName")
#Expose
private String outletName;
#SerializedName("currentBalance")
#Expose
private String currentBalance;
#SerializedName("aepsBalance")
#Expose
private String aepsBalance;
#SerializedName("activationAmount")
#Expose
private String activationAmount;
#SerializedName("transactionAmount")
#Expose
private String transactionAmount;
#SerializedName("totalAmount")
#Expose
private String totalAmount;
#SerializedName("isPaid")
#Expose
private String isPaid;
#SerializedName("rentalType")
#Expose
private String rentalType;
#SerializedName("instagramUrl")
#Expose
private String instagramUrl;
#SerializedName("twitterUrl")
#Expose
private String twitterUrl;
#SerializedName("facebookUrl")
#Expose
private String facebookUrl;
#SerializedName("youtubeUrl")
#Expose
private String youtubeUrl;
#SerializedName("cartItem")
#Expose
private String cartItem;
public String getAepsBalance() {
return aepsBalance;
}
public void setAepsBalance(String aepsBalance) {
this.aepsBalance = aepsBalance;
}
public String getInstagramUrl() {
return instagramUrl;
}
public void setInstagramUrl(String instagramUrl) {
this.instagramUrl = instagramUrl;
}
public String getTwitterUrl() {
return twitterUrl;
}
public void setTwitterUrl(String twitterUrl) {
this.twitterUrl = twitterUrl;
}
public String getFacebookUrl() {
return facebookUrl;
}
public void setFacebookUrl(String facebookUrl) {
this.facebookUrl = facebookUrl;
}
public String getYoutubeUrl() {
return youtubeUrl;
}
public void setYoutubeUrl(String youtubeUrl) {
this.youtubeUrl = youtubeUrl;
}
public String getRentalType() {
return rentalType;
}
public void setRentalType(String rentalType) {
this.rentalType = rentalType;
}
public String getIsPaid() {
return isPaid;
}
public void setIsPaid(String isPaid) {
this.isPaid = isPaid;
}
public String getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(String totalAmount) {
this.totalAmount = totalAmount;
}
public String getTransactionAmount() {
return transactionAmount;
}
public void setTransactionAmount(String transactionAmount) {
this.transactionAmount = transactionAmount;
}
public String getActivationAmount() {
return activationAmount;
}
public void setActivationAmount(String activationAmount) {
this.activationAmount = activationAmount;
}
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getNews() {
return news;
}
public void setNews(String news) {
this.news = news;
}
public JsonArray getBanner() {
return banner;
}
public void setBanner(JsonArray banner) {
this.banner = banner;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getOutletName() {
return outletName;
}
public void setOutletName(String outletName) {
this.outletName = outletName;
}
public String getCartItem() {
return cartItem;
}
public void setCartItem(String cartItem) {
this.cartItem = cartItem;
}
public String getCurrentBalance() {
return currentBalance;
}
public void setCurrentBalance(String currentBalance) {
this.currentBalance = currentBalance;
}
}}
Getting From SharedPreference
String getbanner = preferences.getString(Constants.banner_list, null);
Gson gson = new Gson();
Log.i("bannerdata__", getbanner);
try {
if (getbanner.isEmpty() || getbanner==null || getbanner.equalsIgnoreCase(null)) {
Log.i("bannerdata__", "empty......");
} else {
Type type = new TypeToken<List<String>>() {
}.getType();
List<String> data = gson.fromJson(getbanner, type);
for (String imgstr : data) {
Log.i("bannerdata_2", imgstr);
HashMap<String, String> map = new HashMap<>();
map.put("imgUrl", imgstr);
banner_list.add(map);
}
Banner_adapter adapter1 = new Banner_adapter(banner_list);
snapHelper.attachToRecyclerView(recyclerView);
recyclerView.setAdapter(adapter1);
adapter1.notifyDataSetChanged();
}
} catch (Exception e) {
e.printStackTrace();
}
Add data in SharedPreference
final ArrayList<String> arrPackage = new ArrayList<>();
try {
JSONArray jsonArray2 = new JSONArray(getbalmodel.getMOBILEAPPLICATION().getBanner().toString());
if (banner_list != null) {
banner_list.clear();
}
for (int x = 0; x < jsonArray2.length(); x++) {
String bid = jsonArray2.getJSONObject(x).getString("imgUrl");
arrPackage.add(bid);
Gson gson = new Gson();
String json = gson.toJson(arrPackage);
editor.putString(Constants.banner_list, json);
Log.i("imageurl", bid);
HashMap<String, String> map = new HashMap<>();
map.put("imgUrl", bid);
banner_list.add(map);
}
editor.commit();
} catch (JSONException | NullPointerException e1) {
e1.printStackTrace();
}

Unable to retrieve document - Castexception ParameterizedType

I'm new to mongodb and struggle a bit. I want to store a class which contains a HashMap which contains other objects. When I store the object it works without any error and the document in the database looks good. But retrieving the document results in an error:
Caused by: java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
My (simplified) classes look like this:
#Entity(value = "abbyy_parameters", noClassnameStored = true)
public class AbbyyParameters extends AbstractModifiableMongoBean {
private String wordListEncoding = DEFAULT_ENCODING;
private String description;
private String name;
private PredefinedProfile predefinedProfile;
#Embedded
private CustomProfile customProfile;
private Parameters wordListActionParameters;
private Boolean treatBarcodeAsWord;
private Boolean documentProcessingEnabled;
private Boolean documentExportEnabled;
private Integer ocrPageLimit;
private Boolean highCommaFixEnabled;
private Double skewAngle;
private List<RegexBasedLanguage> regexBasedLanguages = new ArrayList<>(2);
public AbbyyParameters() {
this.createNewId();
this.setPredefinedProfile(new PredefinedProfile(PredefinedProfileType.DEFAULT));
this.setCustomProfile(new CustomProfile());
}
public String getWordListEncoding() {
return wordListEncoding;
}
public void setWordListEncoding(String encoding) {
if (!TangroUtils.isNullOrBlankString(encoding)) {
this.wordListEncoding = encoding;
}
}
public PredefinedProfile getPredefinedProfile() {
return predefinedProfile;
}
public void setPredefinedProfile(PredefinedProfile profile) {
if (profile == null) {
profile = new PredefinedProfile("Default");
}
this.predefinedProfile = profile;
}
public CustomProfile getCustomProfile() {
return customProfile;
}
public void setCustomProfile(CustomProfile profile) {
this.customProfile = profile;
}
public Optional<Boolean> isBarcodeTreatedAsWord() {
return Optional.ofNullable(treatBarcodeAsWord);
}
public void treatBarcodeAsWord(Boolean treatBarcodeAsWord) {
this.treatBarcodeAsWord = treatBarcodeAsWord;
}
public Optional<Boolean> isDocumentProcessingEnabled() {
return Optional.ofNullable(documentProcessingEnabled);
}
public void enableDocumentProcessing(Boolean enableDocumentProcessing) {
this.documentProcessingEnabled = enableDocumentProcessing;
}
public Optional<Boolean> isDocumentExportEnabled() {
return Optional.ofNullable(documentExportEnabled);
}
public void enableDocumentExport(Boolean exportDocument) {
this.documentExportEnabled = exportDocument;
}
public Optional<String> getDescription() {
return Optional.ofNullable(description);
}
public void setDescription(String description) {
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
#Entity
public class CustomProfile {
private static final String DEFAULT_FILE_NAME = "custom";
#Transient
private String name;
#Embedded
private Map<String, ProfileProperties> properties = new HashMap<>(5);
public CustomProfile() {
}
public String getName() {
return name;
}
private void setName (String name) {
this.name = name;
}
public Map<String, ProfileProperties> getProperties() {
return properties;
}
private void setProperties(Map<String, ProfileProperties> properties) {
this.properties = properties;
}
}
#Embedded
public class ProfileProperties implements Iterable<ProfileProperty>, Serializable {
private static final long serialVersionUID = 1L;
#Embedded
private List<ProfileProperty> properties = new ArrayList<>(15);
public List<ProfileProperty> getProperties() {
return properties;
}
public void setProperties(List<ProfileProperty> properties) {
this.properties = properties;
}
public void add(ProfileProperty property) {
Optional<ProfileProperty> oldPropertyOpt = get(property.getName());
if (oldPropertyOpt.isPresent()) {
ProfileProperty oldProperty = oldPropertyOpt.get();
oldProperty.setValue(property.getValue());
} else {
properties.add(property);
}
}
public Optional<ProfileProperty> get(String propertyName) {
if (propertyName == null) {
return Optional.empty();
}
for(ProfileProperty property : properties) {
if (propertyName.equals(property.getName())) {
return Optional.of(property);
}
}
return Optional.empty();
}
#Override
public Iterator<ProfileProperty> iterator() {
return properties.iterator();
}
}
#Embedded
public class ProfileProperty implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private String value;
public ProfileProperty(String name, String value) {
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
I created morphia and told it how to map:
morphia = new Morphia();
morphia.map(AbbyyParameters.class,
CustomProfile.class,
ProfileProperties.class,
ProfileProperty.class);
After storing the class in the database the document look like this:
{
"_id" : ObjectId("5b2906a0cac45b8d42bbda91"),
"wordListEncoding" : "ISO-8859-15",
"description" : "",
"name" : "1",
"predefinedProfile" : {
"type" : "DEFAULT"
},
"customProfile" : {
"properties" : {
"PageAnalysisParams" : {
"properties" : [
{
"name" : "DetectBarcodes",
"value" : "true"
}
]
},
"RecognizerParams" : {
"properties" : [
{
"name" : "TextLanguage",
"value" : "English,German,Digits,French,Italian,Spanish,Croatian,Slovak,Bulgarian"
}
]
}
}
},
"treatBarcodeAsWord" : false,
"documentExportEnabled" : false,
"creationDate" : ISODate("2018-06-19T13:35:26.019Z"),
"changedDate" : ISODate("2018-06-19T13:35:28.441Z")
}
When I try to retrieve the document I get the following error:
Caused by: java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
at org.mongodb.morphia.mapping.EmbeddedMapper.readMap(EmbeddedMapper.java:166)
I stepped into the code so I found that this code raises the exception:
new EphemeralMappedField((ParameterizedType) mf.getSubType(), mf, mapper);
mf.getSubType() returns ProfileProperties so I guess I have misconfigured something there?
What do I have to do that I can retrieve my document?

Assigning multiple Retrofit response values to an arraylist

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?

Java - not able to load json string to object, every element is null

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);

JSON Exception - No value for in Android

I am getting this error message in my logcat 03-18 12:06:36.972: W/System.err(24574): org.json.JSONException: No value for title an I am stuck here. I am using Gson to parse JSON data. Here is my MainActivity and Model class.
I looked into other questions posted for same JSON Exception but I couldn't find the solution so I posted this question for my project
Also please advise if I am using correct method to display the data in the textview.
MainActivity
public class MainActivity extends AppCompatActivity {
public static final String Logcat = "vmech";
Button searchButton;
EditText editTextSearch;
TextView textViewDisplayResult;
String newText;
String urlstring;
public static final String MyAPIKey = "Your_Api_Key";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
searchButton = (Button) findViewById(R.id.buttonSerch);
editTextSearch = (EditText) findViewById(R.id.editTextSearch);
textViewDisplayResult = (TextView) findViewById(R.id.textViewDisplayResult);
searchButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
newText = editTextSearch.getText().toString();
if(newText.length()>0){
newText = newText.replace(" ", "+");
urlstring = "https://www.googleapis.com/books/v1/volumes?q=";
urlstring = urlstring + newText + "&maxResults=5" + "&key=" + MyAPIKey;
}
else {
Toast.makeText(MainActivity.this, "Please enter a book name to search.", Toast.LENGTH_LONG).show();
}
new JSONTask().execute(urlstring);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
Toast.makeText(this, "This is the Settings item", Toast.LENGTH_LONG).show();
return true;
}
public class JSONTask extends AsyncTask<String, String, List<BookInfoModel>>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected List<BookInfoModel> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader bufferedReader = null;
try {
URL url = new URL(urlstring);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream inputstream = connection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputstream));
StringBuffer stringbuffer = new StringBuffer();
String line = "";
while ((line = bufferedReader.readLine()) != null) {
stringbuffer.append(line);
}
String finalJson = stringbuffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("items");
List<BookInfoModel> bookInfoModelList = new ArrayList<>();
String idText = null;
Gson gson = new Gson();
for(int i=0; i<parentArray.length(); i++){
JSONObject finalObject = parentArray.getJSONObject(i);
BookInfoModel bookInfoModel = gson.fromJson(finalObject.toString(),BookInfoModel.class);
bookInfoModelList.add(bookInfoModel);
}
return bookInfoModelList;
} catch (IOException e){
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null)
{
connection.disconnect();
}
try {
if (bufferedReader != null){
bufferedReader.close();
}
}catch (IOException e){
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<BookInfoModel> result) {
super.onPostExecute(result);
textViewDisplayResult.setText((CharSequence) result);
}
}
}
Here is my model class for JSON data.
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class BookInfoModel {
private List<Items> items;
private String totalItems;
private String kind;
public List<Items> getItems() {
return items;
}
public void setItems(List<Items> items) {
this.items = items;
}
public String getTotalItems ()
{
return totalItems;
}
public void setTotalItems (String totalItems)
{
this.totalItems = totalItems;
}
public String getKind ()
{
return kind;
}
public void setKind (String kind)
{
this.kind = kind;
}
public class Items
{
private SaleInfo saleInfo;
private String id;
private SearchInfo searchInfo;
private String etag;
private List<VolumeInfo> volumeInfo;
private String selfLink;
private AccessInfo accessInfo;
private String kind;
public SaleInfo getSaleInfo ()
{
return saleInfo;
}
public void setSaleInfo (SaleInfo saleInfo)
{
this.saleInfo = saleInfo;
}
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public SearchInfo getSearchInfo ()
{
return searchInfo;
}
public void setSearchInfo (SearchInfo searchInfo)
{
this.searchInfo = searchInfo;
}
public String getEtag ()
{
return etag;
}
public void setEtag (String etag)
{
this.etag = etag;
}
public List<VolumeInfo> getVolumeInfo() {
return volumeInfo;
}
public void setVolumeInfo(List<VolumeInfo> volumeInfo) {
this.volumeInfo = volumeInfo;
}
public String getSelfLink ()
{
return selfLink;
}
public void setSelfLink (String selfLink)
{
this.selfLink = selfLink;
}
public AccessInfo getAccessInfo ()
{
return accessInfo;
}
public void setAccessInfo (AccessInfo accessInfo)
{
this.accessInfo = accessInfo;
}
public String getKind ()
{
return kind;
}
public void setKind (String kind)
{
this.kind = kind;
}
public class SearchInfo
{
private String textSnippet;
public String getTextSnippet ()
{
return textSnippet;
}
public void setTextSnippet (String textSnippet)
{
this.textSnippet = textSnippet;
}
}
public class AccessInfo
{
private String webReaderLink;
private String textToSpeechPermission;
private String publicDomain;
private String viewability;
private String accessViewStatus;
private Pdf pdf;
private Epub epub;
private String embeddable;
private String quoteSharingAllowed;
private String country;
public String getWebReaderLink ()
{
return webReaderLink;
}
public void setWebReaderLink (String webReaderLink)
{
this.webReaderLink = webReaderLink;
}
public String getTextToSpeechPermission ()
{
return textToSpeechPermission;
}
public void setTextToSpeechPermission (String textToSpeechPermission)
{
this.textToSpeechPermission = textToSpeechPermission;
}
public String getPublicDomain ()
{
return publicDomain;
}
public void setPublicDomain (String publicDomain)
{
this.publicDomain = publicDomain;
}
public String getViewability ()
{
return viewability;
}
public void setViewability (String viewability)
{
this.viewability = viewability;
}
public String getAccessViewStatus ()
{
return accessViewStatus;
}
public void setAccessViewStatus (String accessViewStatus)
{
this.accessViewStatus = accessViewStatus;
}
public Pdf getPdf ()
{
return pdf;
}
public void setPdf (Pdf pdf)
{
this.pdf = pdf;
}
public Epub getEpub ()
{
return epub;
}
public void setEpub (Epub epub)
{
this.epub = epub;
}
public String getEmbeddable ()
{
return embeddable;
}
public void setEmbeddable (String embeddable)
{
this.embeddable = embeddable;
}
public String getQuoteSharingAllowed ()
{
return quoteSharingAllowed;
}
public void setQuoteSharingAllowed (String quoteSharingAllowed)
{
this.quoteSharingAllowed = quoteSharingAllowed;
}
public String getCountry ()
{
return country;
}
public void setCountry (String country)
{
this.country = country;
}
public class Pdf
{
private String acsTokenLink;
private String isAvailable;
public String getAcsTokenLink ()
{
return acsTokenLink;
}
public void setAcsTokenLink (String acsTokenLink)
{
this.acsTokenLink = acsTokenLink;
}
public String getIsAvailable ()
{
return isAvailable;
}
public void setIsAvailable (String isAvailable)
{
this.isAvailable = isAvailable;
}
}
public class Epub
{
private String acsTokenLink;
private String isAvailable;
public String getAcsTokenLink ()
{
return acsTokenLink;
}
public void setAcsTokenLink (String acsTokenLink)
{
this.acsTokenLink = acsTokenLink;
}
public String getIsAvailable ()
{
return isAvailable;
}
public void setIsAvailable (String isAvailable)
{
this.isAvailable = isAvailable;
}
}
}
public class SaleInfo
{
private RetailPrice retailPrice;
private String saleability;
private ListPrice listPrice;
private Offers[] offers;
private String buyLink;
private String isEbook;
private String country;
public RetailPrice getRetailPrice ()
{
return retailPrice;
}
public void setRetailPrice (RetailPrice retailPrice)
{
this.retailPrice = retailPrice;
}
public String getSaleability ()
{
return saleability;
}
public void setSaleability (String saleability)
{
this.saleability = saleability;
}
public ListPrice getListPrice ()
{
return listPrice;
}
public void setListPrice (ListPrice listPrice)
{
this.listPrice = listPrice;
}
public Offers[] getOffers ()
{
return offers;
}
public void setOffers (Offers[] offers)
{
this.offers = offers;
}
public String getBuyLink ()
{
return buyLink;
}
public void setBuyLink (String buyLink)
{
this.buyLink = buyLink;
}
public String getIsEbook ()
{
return isEbook;
}
public void setIsEbook (String isEbook)
{
this.isEbook = isEbook;
}
public String getCountry ()
{
return country;
}
public void setCountry (String country)
{
this.country = country;
}
public class Offers
{
private RetailPrice retailPrice;
private ListPrice listPrice;
private String finskyOfferType;
public RetailPrice getRetailPrice ()
{
return retailPrice;
}
public void setRetailPrice (RetailPrice retailPrice)
{
this.retailPrice = retailPrice;
}
public ListPrice getListPrice ()
{
return listPrice;
}
public void setListPrice (ListPrice listPrice)
{
this.listPrice = listPrice;
}
public String getFinskyOfferType ()
{
return finskyOfferType;
}
public void setFinskyOfferType (String finskyOfferType)
{
this.finskyOfferType = finskyOfferType;
}
}
public class RetailPrice
{
private String amount;
private String currencyCode;
public String getAmount ()
{
return amount;
}
public void setAmount (String amount)
{
this.amount = amount;
}
public String getCurrencyCode ()
{
return currencyCode;
}
public void setCurrencyCode (String currencyCode)
{
this.currencyCode = currencyCode;
}
}
public class ListPrice
{
private String amount;
private String currencyCode;
public String getAmount ()
{
return amount;
}
public void setAmount (String amount)
{
this.amount = amount;
}
public String getCurrencyCode ()
{
return currencyCode;
}
public void setCurrencyCode (String currencyCode)
{
this.currencyCode = currencyCode;
}
}
}
public class VolumeInfo
{
private String pageCount;
private String averageRating;
private ReadingModes readingModes;
private String infoLink;
private String printType;
private String allowAnonLogging;
private String publisher;
private String[] authors;
private String canonicalVolumeLink;
#SerializedName("title")
private String title;
private String previewLink;
private String description;
private String ratingsCount;
private ImageLinks imageLinks;
private String contentVersion;
private String[] categories;
private String language;
private String publishedDate;
private IndustryIdentifiers[] industryIdentifiers;
private String maturityRating;
public String getPageCount ()
{
return pageCount;
}
public void setPageCount (String pageCount)
{
this.pageCount = pageCount;
}
public String getAverageRating ()
{
return averageRating;
}
public void setAverageRating (String averageRating)
{
this.averageRating = averageRating;
}
public ReadingModes getReadingModes ()
{
return readingModes;
}
public void setReadingModes (ReadingModes readingModes)
{
this.readingModes = readingModes;
}
public String getInfoLink ()
{
return infoLink;
}
public void setInfoLink (String infoLink)
{
this.infoLink = infoLink;
}
public String getPrintType ()
{
return printType;
}
public void setPrintType (String printType)
{
this.printType = printType;
}
public String getAllowAnonLogging ()
{
return allowAnonLogging;
}
public void setAllowAnonLogging (String allowAnonLogging)
{
this.allowAnonLogging = allowAnonLogging;
}
public String getPublisher ()
{
return publisher;
}
public void setPublisher (String publisher)
{
this.publisher = publisher;
}
public String[] getAuthors ()
{
return authors;
}
public void setAuthors (String[] authors)
{
this.authors = authors;
}
public String getCanonicalVolumeLink ()
{
return canonicalVolumeLink;
}
public void setCanonicalVolumeLink (String canonicalVolumeLink)
{
this.canonicalVolumeLink = canonicalVolumeLink;
}
public String getTitle ()
{
return title;
}
public void setTitle (String title)
{
this.title = title;
}
public String getPreviewLink ()
{
return previewLink;
}
public void setPreviewLink (String previewLink)
{
this.previewLink = previewLink;
}
public String getDescription ()
{
return description;
}
public void setDescription (String description)
{
this.description = description;
}
public String getRatingsCount ()
{
return ratingsCount;
}
public void setRatingsCount (String ratingsCount)
{
this.ratingsCount = ratingsCount;
}
public ImageLinks getImageLinks ()
{
return imageLinks;
}
public void setImageLinks (ImageLinks imageLinks)
{
this.imageLinks = imageLinks;
}
public String getContentVersion ()
{
return contentVersion;
}
public void setContentVersion (String contentVersion)
{
this.contentVersion = contentVersion;
}
public String[] getCategories ()
{
return categories;
}
public void setCategories (String[] categories)
{
this.categories = categories;
}
public String getLanguage ()
{
return language;
}
public void setLanguage (String language)
{
this.language = language;
}
public String getPublishedDate ()
{
return publishedDate;
}
public void setPublishedDate (String publishedDate)
{
this.publishedDate = publishedDate;
}
public IndustryIdentifiers[] getIndustryIdentifiers ()
{
return industryIdentifiers;
}
public void setIndustryIdentifiers (IndustryIdentifiers[] industryIdentifiers)
{
this.industryIdentifiers = industryIdentifiers;
}
public String getMaturityRating ()
{
return maturityRating;
}
public void setMaturityRating (String maturityRating)
{
this.maturityRating = maturityRating;
}
public class ImageLinks
{
private String thumbnail;
private String smallThumbnail;
public String getThumbnail ()
{
return thumbnail;
}
public void setThumbnail (String thumbnail)
{
this.thumbnail = thumbnail;
}
public String getSmallThumbnail ()
{
return smallThumbnail;
}
public void setSmallThumbnail (String smallThumbnail)
{
this.smallThumbnail = smallThumbnail;
}
}
public class ReadingModes
{
private String text;
private String image;
public String getText ()
{
return text;
}
public void setText (String text)
{
this.text = text;
}
public String getImage ()
{
return image;
}
public void setImage (String image)
{
this.image = image;
}
}
public class IndustryIdentifiers
{
private String type;
private String identifier;
public String getType ()
{
return type;
}
public void setType (String type)
{
this.type = type;
}
public String getIdentifier ()
{
return identifier;
}
public void setIdentifier (String identifier)
{
this.identifier = identifier;
}
}
}
}
}
Here is the JSON data I m trying to Parse.
{
"kind": "books#volumes",
"totalItems": 1557,
"items": [
{
"kind": "books#volume",
"id": "An4_e3Cr3zAC",
"etag": "DWmqBRkB8dw",
"selfLink": "https://www.googleapis.com/books/v1/volumes/An4_e3Cr3zAC",
"volumeInfo": {
"title": "The Rules of the Game",
"authors": [
"Neil Strauss"
],
"publisher": "Canongate Books",
"publishedDate": "2011-09-29",
"description": "If you want to play The Game you need to know The Rules This book is not a story.",
"industryIdentifiers": [
{
"type": "ISBN_13",
"identifier": "9781847673558"
},
{
"type": "ISBN_10",
"identifier": "1847673554"
}
],
"readingModes": {
"text": true,
"image": true
},
"pageCount": 352,
"printType": "BOOK",
"categories": [
"Biography & Autobiography"
],
"averageRating": 3.5,
"ratingsCount": 82,
"maturityRating": "NOT_MATURE",
"allowAnonLogging": true,
"contentVersion": "1.7.6.0.preview.3",
"imageLinks": {
"smallThumbnail": "http://books.google.co.in/books/content?id=An4_e3Cr3zAC&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api",
"thumbnail": "http://books.google.co.in/books/content?id=An4_e3Cr3zAC&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api"
},
"language": "en",
"previewLink": "http://books.google.co.in/books?id=An4_e3Cr3zAC&printsec=frontcover&dq=game&hl=&cd=1&source=gbs_api",
"infoLink": "http://books.google.co.in/books?id=An4_e3Cr3zAC&dq=game&hl=&source=gbs_api",
"canonicalVolumeLink": "http://books.google.co.in/books/about/The_Rules_of_the_Game.html?hl=&id=An4_e3Cr3zAC"
},
"saleInfo": {
"country": "IN",
"saleability": "FOR_SALE",
"isEbook": true,
"listPrice": {
"amount": 399.0,
"currencyCode": "INR"
},
"retailPrice": {
"amount": 279.3,
"currencyCode": "INR"
},
"buyLink": "http://books.google.co.in/books?id=An4_e3Cr3zAC&dq=game&hl=&buy=&source=gbs_api",
"offers": [
{
"finskyOfferType": 1,
"listPrice": {
"amountInMicros": 3.99E8,
"currencyCode": "INR"
},
"retailPrice": {
"amountInMicros": 2.793E8,
"currencyCode": "INR"
}
}
]
},
"accessInfo": {
"country": "IN",
"viewability": "PARTIAL",
"embeddable": true,
"publicDomain": false,
"textToSpeechPermission": "ALLOWED",
"epub": {
"isAvailable": true,
"acsTokenLink": "http://books.goo"
},
"pdf": {
"isAvailable": true,
"acsTokenLink": "http://books.google.co.in/books/download/The_Rules_of_the_Game-sample-pdf.acsm?id=An4_e3Cr3zAC&format=pdf&output=acs4_fulfillment_token&dl_type=sample&source=gbs_api"
},
"webReaderLink": "http://books.google.co.in/books/reader?id=An4_e3Cr3zAC&hl=&printsec=frontcover&output=reader&source=gbs_api",
"accessViewStatus": "SAMPLE",
"quoteSharingAllowed": false
},
"searchInfo": {
"textSnippet": "He's tested the specific material."
}
}
]
}
Here is the stacktrace form logcat. https://codeshare.io/Ag78v
Replace your Items class with below:
public class Items
{
private SaleInfo saleInfo;
private String id;
private SearchInfo searchInfo;
private String etag;
private VolumeInfo volumeInfo;
private String selfLink;
private AccessInfo accessInfo;
private String kind;
public SaleInfo getSaleInfo ()
{
return saleInfo;
}
public void setSaleInfo (SaleInfo saleInfo)
{
this.saleInfo = saleInfo;
}
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public SearchInfo getSearchInfo ()
{
return searchInfo;
}
public void setSearchInfo (SearchInfo searchInfo)
{
this.searchInfo = searchInfo;
}
public String getEtag ()
{
return etag;
}
public void setEtag (String etag)
{
this.etag = etag;
}
public VolumeInfo getVolumeInfo() {
return volumeInfo;
}
public void setVolumeInfo(VolumeInfo volumeInfo) {
this.volumeInfo = volumeInfo;
}
public String getSelfLink ()
{
return selfLink;
}
public void setSelfLink (String selfLink)
{
this.selfLink = selfLink;
}
public AccessInfo getAccessInfo ()
{
return accessInfo;
}
public void setAccessInfo (AccessInfo accessInfo)
{
this.accessInfo = accessInfo;
}
public String getKind ()
{
return kind;
}
public void setKind (String kind)
{
this.kind = kind;
}
}
You are not using the serializedName annotation. Use it as follows in your model.
public class Items
{
#SerializedName("Your-key-from JSON Response")
private SaleInfo saleInfo;
#SerializedName("Your-key-from JSON Response")
private String id;
#SerializedName("Your-key-from JSON Response")
private SearchInfo searchInfo;
#SerializedName("Your-key-from JSON Response")
private String etag;
#SerializedName("Your-key-from JSON Response")
private VolumeInfo volumeInfo;
#SerializedName("Your-key-from JSON Response")
private String selfLink;
#SerializedName("Your-key-from JSON Response")
private AccessInfo accessInfo;
#SerializedName("Your-key-from JSON Response")
private String kind;
public SaleInfo getSaleInfo ()
{
return saleInfo;
}
public void setSaleInfo (SaleInfo saleInfo)
{
this.saleInfo = saleInfo;
}
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
}
One of Your ListItem VolumeInfo have null value for title. By default Gson wont parse null value. But you can make to ignore null values when parsing. by doing the following.
Gson gson = new GsonBuilder().serializeNulls().create();
Try this.

Categories