Refer to Object from server response - android

On the server there is (as I understand it) an object. It has 2 values ​​- the text and the color of this text. So - I need to get this text and color. At the moment everything is displayed together - TextView is passed the value [{"text": "WE RETURN 10% BONUSES", "textColor": "# 4c82a6"}] ,.
I need to get these values ​​separately
"tag": [
{
"text": "ВЕРНЕМ 10% БОНУСАМИ",
"textColor": "#4c82a6"
}
],
Model
public class Item {
#SerializedName("id")
#Expose
private String id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("image")
#Expose
private String image;
#SerializedName("isFavorite")
#Expose
private boolean isFavorite;
#SerializedName("prices")
#Expose
private Prices prices;
#SerializedName("full_set_prices")
#Expose
private Object fullSetPrices;
#SerializedName("isBestPrice")
#Expose
private boolean isBestPrice;
#SerializedName("tag")
#Expose
private Object tag;
#SerializedName("articul")
#Expose
private String articul;
#SerializedName("rating")
#Expose
private double rating;
#SerializedName("numberOfReviews")
#Expose
private int numberOfReviews;
#SerializedName("statusText")
#Expose
private String statusText;
#SerializedName("isAvailable")
#Expose
private boolean isAvailable;
#SerializedName("images")
#Expose
private List<String> images = null;
#SerializedName("categoryId")
#Expose
private String categoryId;
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getImage() {
return image;
}
public boolean isIsFavorite() {
return isFavorite;
}
public Prices getPrices() {
return prices;
}
public Object getFullSetPrices() {
return fullSetPrices;
}
public boolean isIsBestPrice() {
return isBestPrice;
}
public Object getTag() {
return tag;
}
public void setTag(Object tag) {
this.tag = tag;
}
public String getArticul() {
return articul;
}
public void setArticul(String articul) {
this.articul = articul;
}
public double getRating() {
return rating;
}
public void setRating(double rating) {
this.rating = rating;
}
public int getNumberOfReviews() {
return numberOfReviews;
}
public void setNumberOfReviews(int numberOfReviews) {
this.numberOfReviews = numberOfReviews;
}
public String getStatusText() {
return statusText;
}
public void setStatusText(String statusText) {
this.statusText = statusText;
}
public boolean isIsAvailable() {
return isAvailable;
}
public void setIsAvailable(boolean isAvailable) {
this.isAvailable = isAvailable;
}
public List<String> getImages() {
return images;
}
public void setImages(List<String> images) {
this.images = images;
}
public String getCategoryId() {
return categoryId;
}
public void setCategoryId(String categoryId) {
this.categoryId = categoryId;
}
}

You could create another POJO for the tag instead of using Object.
public class Item {
...
#SerializedName("tag")
#Expose
private Tag tag;
...
}
public class Tag {
#SerializedName("text")
#Expose
private String text;
#SerializedName("textColor")
#Expose
private String textColor;
}
Then you can access the new values with item.getTag().getText(). Or if you'd rather make it appear that the two Tag fields are part of Item, you can create methods that delegate to Tag:
public class Item {
...
public String getText() {
return this.tag.getText();
}
public String getTextColor() {
return this.tag.getTextColor();
}
...
}

Related

Java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY when want to get data into recyclerview

I have a json. I have to get source_url into my recyclerView -
[{
"id":3110,
"date":"2020-05-07T18:33:44",
"date_gmt":"2020-05-07T18:33:44",
"modified":"2020-05-07T18:35:37",
"modified_gmt":"2020-05-07T18:35:37",
"_embedded":{
"wp:featuredmedia":[
{
"id":3111,
"date":"2020-05-07T18:33:08",
"slug":"prof-dr-abul-khair",
"source_url":"https:\/\/www.healthmen.com.bd\/wpcontent\/uploads\/2020\/05\/Prof.-Dr.-Abul-Khair-scaled.jpg"
}]
}
}]
I want to get source_url from this JSON
But, here is an array wp:featuredmedia. So that, I followed this process-
Created a class named FeaturedMedia -
public class FeaturedMedia {
#SerializedName("source_url")
#Expose
private String souceurl;
public String getSourceurl(){
return sourceurl;
}
}
Then, I created another class named MediaDetails where I take the FeaturedMedia as a List-
public class MediaDetails{
#SerializedName("wp:featuredmedia")
List<FeaturedMedia> featureMediaList;
public List<FeaturedMedia> getFeaturedMediaList(){
return featuredMediaList;
}}
Then the Model Class-
public class Model{
#SerializedName("id")
#Expose
int id;
#SerializedName("_embedded")
#Expose
MediaDetalis embedded;
public int getId(){
return id;
}
public MediaDetails getEmbedded(){
return embedded;
}}
After all, I created RecyclerViewAdapter to get the data-
public CustomAdapter extends RecyclerView.Adapter<CustomAdapter.CustomAdapterHolder{
List<Model> modelList;
public void onBindViewHolder(#NonNull CustomAdapterHolder holder, int position){
final Model model=modelList.get(position);
int id= model.getId():
String embedded= String.valurOf(model.getEmbedded.getFeaturedMediaList());
}
But, embedded can not get the source_url value. I completed this CustomAdapter. Here I just presented needed code of that adapter. How can I get the source_url value in this RecyclerView?
Your POJO class will be (Respect to given JSON)
public class Model {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("date")
#Expose
private String date;
#SerializedName("date_gmt")
#Expose
private String dateGmt;
#SerializedName("modified")
#Expose
private String modified;
#SerializedName("modified_gmt")
#Expose
private String modifiedGmt;
#SerializedName("_embedded")
#Expose
private Embedded embedded;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getDateGmt() {
return dateGmt;
}
public void setDateGmt(String dateGmt) {
this.dateGmt = dateGmt;
}
public String getModified() {
return modified;
}
public void setModified(String modified) {
this.modified = modified;
}
public String getModifiedGmt() {
return modifiedGmt;
}
public void setModifiedGmt(String modifiedGmt) {
this.modifiedGmt = modifiedGmt;
}
public Embedded getEmbedded() {
return embedded;
}
public void setEmbedded(Embedded embedded) {
this.embedded = embedded;
}
}
Then Embedded class
public class Embedded {
#SerializedName("wp:featuredmedia")
#Expose
private List<WpFeaturedmedium> wpFeaturedmedia = null;
public List<WpFeaturedmedium> getWpFeaturedmedia() {
return wpFeaturedmedia;
}
public void setWpFeaturedmedia(List<WpFeaturedmedium> wpFeaturedmedia) {
this.wpFeaturedmedia = wpFeaturedmedia;
}
}
Then WpFeaturedmedium
public class WpFeaturedmedium {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("date")
#Expose
private String date;
#SerializedName("slug")
#Expose
private String slug;
#SerializedName("source_url")
#Expose
private String sourceUrl;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public String getSourceUrl() {
return sourceUrl;
}
public void setSourceUrl(String sourceUrl) {
this.sourceUrl = sourceUrl;
}
}
Check - How to create POJO class

add object into GSON array android studio

hey guys im using android's gson library to parse my JSON. everything is working fine in that I have that selected goal array sometimes it is full of values and sometimes it is an empty array. when array is empty I want to push an object init when I try to add its index
selected_goal.add(INDEX,VALUE)
I want to push an object at the place of value please help me how can I do it…
this is my pojo:
public class SelectedGoal {
#SerializedName("id")
#Expose
private String id;
#SerializedName("goal_name")
#Expose
private String goalName;
#SerializedName("image")
#Expose
private String image;
#SerializedName("position")
#Expose
private String position;
#SerializedName("athlete_id")
#Expose
private String athleteId;
#SerializedName("coach_id")
#Expose
private String coachId;
#SerializedName("current_goal_id")
#Expose
private String currentGoalId;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getGoalName() {
return goalName;
}
public void setGoalName(String goalName) {
this.goalName = goalName;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
public String getAthleteId() {
return athleteId;
}
public void setAthleteId(String athleteId) {
this.athleteId = athleteId;
}
public String getCoachId() {
return coachId;
}
public void setCoachId(String coachId) {
this.coachId = coachId;
}
public String getCurrentGoalId() {
return currentGoalId;
}
public void setCurrentGoalId(String currentGoalId) {
this.currentGoalId = currentGoalId;
}
}
selected_goal.add(INDEX,new SelectedGoal());
EDIT- To set values, make constuctor in your SelectedGoal class like.
public SelectedGoal(String id, String goalName, String image, String
position, String athleteId, String coachId, String currentGoalId) {
this.id = id;
this.goalName = goalName;
this.image = image;
this.position = position;
this.athleteId = athleteId;
this.coachId = coachId;
this.currentGoalId = currentGoalId;
}
finally add your object into list like..
selected_goal.add(INDEX,new SelectedGoal(id,goalName,image,position,athleteId,coachId,currentGoalId));

Trying to use GSON with OpenWeather API

I'm trying to use GSON with my OpenWeatherMap API. I was able to parse my JSON into the following code:
public class List {
#SerializedName("dt")
#Expose
private Integer dt;
#SerializedName("main")
#Expose
private Main main;
#SerializedName("weather")
#Expose
private java.util.List<Weather> weather = null;
#SerializedName("clouds")
#Expose
private Clouds clouds;
#SerializedName("wind")
#Expose
private Wind wind;
#SerializedName("rain")
#Expose
private Rain rain;
#SerializedName("sys")
#Expose
private Sys sys;
#SerializedName("dt_txt")
#Expose
private String dtTxt;
public Integer getDt() {
return dt;
}
public void setDt(Integer dt) {
this.dt = dt;
}
public Main getMain() {
return main;
}
public void setMain(Main main) {
this.main = main;
}
public java.util.List<Weather> getWeather() {
return weather;
}
public void setWeather(java.util.List<Weather> weather) {
this.weather = weather;
}
public Clouds getClouds() {
return clouds;
}
public void setClouds(Clouds clouds) {
this.clouds = clouds;
}
public Wind getWind() {
return wind;
}
public void setWind(Wind wind) {
this.wind = wind;
}
public Rain getRain() {
return rain;
}
public void setRain(Rain rain) {
this.rain = rain;
}
public Sys getSys() {
return sys;
}
public void setSys(Sys sys) {
this.sys = sys;
}
public String getDtTxt() {
return dtTxt;
}
public void setDtTxt(String dtTxt) {
this.dtTxt = dtTxt;
}
}
public class Main {
#SerializedName("temp")
#Expose
private Double temp;
#SerializedName("temp_min")
#Expose
private Double tempMin;
#SerializedName("temp_max")
#Expose
private Double tempMax;
#SerializedName("pressure")
#Expose
private Double pressure;
#SerializedName("sea_level")
#Expose
private Double seaLevel;
#SerializedName("grnd_level")
#Expose
private Double grndLevel;
#SerializedName("humidity")
#Expose
private Integer humidity;
#SerializedName("temp_kf")
#Expose
private Integer tempKf;
public Double getTemp() {
return temp;
}
public void setTemp(Double temp) {
this.temp = temp;
}
public Double getTempMin() {
return tempMin;
}
public void setTempMin(Double tempMin) {
this.tempMin = tempMin;
}
public Double getTempMax() {
return tempMax;
}
public void setTempMax(Double tempMax) {
this.tempMax = tempMax;
}
public Double getPressure() {
return pressure;
}
public void setPressure(Double pressure) {
this.pressure = pressure;
}
public Double getSeaLevel() {
return seaLevel;
}
public void setSeaLevel(Double seaLevel) {
this.seaLevel = seaLevel;
}
public Double getGrndLevel() {
return grndLevel;
}
public void setGrndLevel(Double grndLevel) {
this.grndLevel = grndLevel;
}
public Integer getHumidity() {
return humidity;
}
public void setHumidity(Integer humidity) {
this.humidity = humidity;
}
public Integer getTempKf() {
return tempKf;
}
public void setTempKf(Integer tempKf) {
this.tempKf = tempKf;
}
}
public class Weather {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("main")
#Expose
private String main;
#SerializedName("description")
#Expose
private String description;
#SerializedName("icon")
#Expose
private String icon;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getMain() {
return main;
}
public void setMain(String main) {
this.main = main;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
}
I've been searching online and on here and I have been unable to find how exactly to use GSON with my code which is:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_weather_app, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecyclerView.addItemDecoration(new DividerItemDecoration(mRecyclerView.getContext(), DividerItemDecoration.VERTICAL));
requestJsonObject();
return view;
}
private void requestJsonObject (){
}
How exactly do I add the GSON parsing to my code? I only need the temperature, max, min, weather and humidity?
EDIT:
Here is some more info. I plan on using a normal http connection with an apikey to get my information. I am also planning on using RecyclerView and here is that code:
public class RecyclerViewAdapter extends
RecyclerView.Adapter<RecyclerViewAdapter.CurrentRecycler> {
List<Weather> mCurrentWeatherDataList;
public static class CurrentRecycler extends RecyclerView.ViewHolder{
public TextView location;
public TextView currentTemp;
public TextView currentHumidity;
public TextView currentDescription;
public ImageView currentIcon;
public CurrentRecycler (View view) {
super (view);
location = (TextView) view.findViewById(R.id.current_city_location);
currentTemp = (TextView) view.findViewById(R.id.current_temperature);
currentHumidity = (TextView) view.findViewById(R.id.current_humidity);
currentDescription = (TextView) view.findViewById(R.id.current_weather_description);
currentIcon = (ImageView) view.findViewById(R.id.current_weather_icon);
}
}
public RecyclerViewAdapter (List<Weather> mCurrentWeatherDataList) {
this.mCurrentWeatherDataList = mCurrentWeatherDataList;
}
#Override
public CurrentRecycler onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item, parent, false);
final CurrentRecycler currentRecycler = new CurrentRecycler(view);
return currentRecycler;
}
#Override
public void onBindViewHolder( CurrentRecycler holder, int position) {
final Weather currentRecycler = mCurrentWeatherDataList.get(position);
holder.location.setText(currentRecycler.getDefaultLocation());
holder.currentTemp.setText((currentRecycler.getDefaultCurrentTemp()));
holder.currentHumidity.setText(currentRecycler.getDefaultHumidity());
holder.currentDescription.setText(currentRecycler.getDefaultDescription());
}
#Override
public int getItemCount() {
return mCurrentWeatherDataList.size();
}
}
In your requestJsonObject method, use volley or okhttp to fetch the weather data from API.
Once you get the data as a String, you can use the following code:
List list = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().fromJson(str, List.class);
Main main = list.getDt();
main.getTemp();
main.getTempMin();
main.getTempMax();
str means your api response data. List means your first entity class.
Moreover, I strongly recommend you to rename your class name, never try to use the reserved name of Java, make them meaningful.

Missing object when using #SerializedName with Retrofit call

I'm developing an Android app which connects to a Springboot server.
The app (using okhttp3 and retrofit) calls the server which returns an array list in an object (Photo Response) below.
The list is populating but the object MediaContentGroup does not populate in any photo object even though the fields of id and title do.
I've debugged through my server to ensure that I am using the correct object names when using #SerializedName.
I'm pretty new to Android development and using springboot, so if anyone could help me to understand why the MediaContentGroup object is always null, I would really appreciate it.
Is there any possible way I've set it to only accept Strings??
Thanks
public class PhotoResponse {
#SerializedName("photoFeed")
#Expose
private PhotoFeed photoFeed;
public PhotoFeed getPhotoFeed() {
return photoFeed;
}
}
public class PhotoFeed {
#SerializedName("photoList")
#Expose
private List<Photo> photoList = new ArrayList<>();
public List<Photo> getPhotoList() {
return photoList;
}
}
public class Photo {
public final static int HD_720_WIDTH = 1280;
public final static int HD_720_HEIGHT = 720;
#SerializedName("id")
#Expose
private String id;
#SerializedName("title")
#Expose
private String title;
#SerializedName("mediaContentGroup")
#Expose
private MediaContentGroup mediaContentGroup;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public void setMediaContentGroup(MediaContentGroup mediaContentGroup){
this.mediaContentGroup = mediaContentGroup;
}
public MediaContentGroup getMediaContentGroup(){
return this.mediaContentGroup;
}
public String getImageUrl() {
return mediaContentGroup.getImages().get(0).getUrl();
}
public String getThumbUrl() {
return mediaContentGroup.getThumbnails().get(0).getUrl();
}
}
public class MediaContentGroup {
#SerializedName("images")
#Expose
public List<MediaContent> images = new ArrayList<>();
public void setImages(List<MediaContent> images){ this.images = images;}
public List<MediaContent> getImages() {
return images;
}
#SerializedName("thumbnails")
#Expose
public List<Thumbnail> thumbnails = new ArrayList<>();
public void setThumbnails(List<Thumbnail> thumbnails){ this.thumbnails = thumbnails;}
public List<Thumbnail> getThumbnails() {
return thumbnails;
}
}
public class Thumbnail {
#SerializedName("url")
#Expose
private String url;
public void setUrl(String url) {
this.url = url;
}
public String getUrl() {
return url;
}
}

how to handle a JSON array object using retrofit?

I am not so new to Android, but started using retrofit today, I was able to clear all errors, now the response body returns null. I know its something to do with the way my class is set up. I have no idea how to handle an array with arrays. Any help would be appreciated. Thanks
[
My Interface
#GET("/web-api.php?route=feed/web_api/products")
Call<Product> loadProducts(#Query("category") Integer id, #Query("key") String apiKey);
Class
public class Product implements Serializable {
#SerializedName("id")
private long mId;
#SerializedName("name")
private String mname;
#SerializedName("description")
private String mText;
#SerializedName("price")
private Double mprice;
#SerializedName("href")
private String mproductURL;
#SerializedName("thumb")
private String mImageURL;
public Product(long mId, String mname, String mText, Double mprice, String mproductURL, String mImageURL) {
this.mId = mId;
this.mname = mname;
this.mText = mText;
this.mprice = mprice;
this.mproductURL = mproductURL;
this.mImageURL = mImageURL;
}
public long getmId() {
return mId;
}
public void setmId(long mId) {
this.mId = mId;
}
public String getMname() {
return mname;
}
public void setMname(String mname) {
this.mname = mname;
}
public String getmText() {
return mText;
}
public void setmText(String mText) {
this.mText = mText;
}
public Double getMprice() {
return mprice;
}
public void setMprice(Double mprice) {
this.mprice = mprice;
}
public String getMproductURL() {
return mproductURL;
}
public void setMproductURL(String mproductURL) {
this.mproductURL = mproductURL;
}
public String getmImageURL() {
return mImageURL;
}
public void setmImageURL(String mImageURL) {
this.mImageURL = mImageURL;
}
#Override
public String toString() {
return mText;
}
}
Just define a Super class -
public class ResponseDS{
public boolean success;
public Product[] products;
}
And use ResponseDS instead of Product class -
#GET("/web-api.php?route=feed/web_api/products")
Call<ResponseDS> loadProducts(#Query("category") Integer id, #Query("key") String apiKey);
Hope it will help :)

Categories

Resources