RoboSpice-Retrofit POJO - android

I have a JSON like this:
{"meta": {...}, "objects": [{...}, {...}]}
But the problem is how to construct the POJO class. From the samples there is only one example with simple JSON.
I tried with something like this:
class Test {
public ArrayList<String> meta;
public static class Object {
public String testField;
}
public static class Objects extends ArrayList<Object>{}
}
And in the RetrofitRequest class I use Test.Objects.class
Any help will be appreciated!

I've fixed it with creating classes for meta and object where objects are in ArrayList<Object>
Thanks!

These are the POJO class to hold and parse the json
1)Meta.java
public class Meta {
private int limit;
private String next;
private int offset;
private String previous;
private int total_count;
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
this.limit = limit;
}
public String getNext() {
return next;
}
public void setNext(String next) {
this.next = next;
}
public int getOffset() {
return offset;
}
public void setOffset(int offset) {
this.offset = offset;
}
public String getPrevious() {
return previous;
}
public void setPrevious(String previous) {
this.previous = previous;
}
public int getTotal_count() {
return total_count;
}
public void setTotal_count(int total_count) {
this.total_count = total_count;
}
}
2)Objects.java
public class Objects {
private String description;
private int downloads;
private int family_filter;
private int id;
private String image_url;
private int rating;
private String resource_uri;
private int size;
private String tags;
private String title;
private String uploaded_date;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getDownloads() {
return downloads;
}
public void setDownloads(int downloads) {
this.downloads = downloads;
}
public int getFamily_filter() {
return family_filter;
}
public void setFamily_filter(int family_filter) {
this.family_filter = family_filter;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getImage_url() {
return image_url;
}
public void setImage_url(String image_url) {
this.image_url = image_url;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
public String getResource_uri() {
return resource_uri;
}
public void setResource_uri(String resource_uri) {
this.resource_uri = resource_uri;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public String getTags() {
return tags;
}
public void setTags(String tags) {
this.tags = tags;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUploaded_date() {
return uploaded_date;
}
public void setUploaded_date(String uploaded_date) {
this.uploaded_date = uploaded_date;
}
}
3) Finally your Test.java
public class Test {
private Meta meta;
private List<Objects> objects;
public Meta getMeta() {
return meta;
}
public void setMeta(Meta meta) {
this.meta = meta;
}
public List<Objects> getObjects() {
return objects;
}
public void setObjects(List<Objects> objects) {
this.objects = objects;
}
}
Try like this.
This is complete POJO class which will hold the parsed json.

Related

How to get JSON Array inside of a JSON Object and iterate

I am trying to communicate with an API using Retrofit in Android Studios but do not know how to get the JSON array within a JSON object.
JSON:
{
"result":{
"status":{
"msg":"success",
"code":200,
"action":2,
"execution_time":"0.505"
},
"page":"1",
"page_size":"40",
"q":"iphone",
"sort":"default",
"tmall":false,
"free_shiping":false,
"total_results":1924963,
"ip":"13.228.169.5",
"item":[
{
"num_iid":619354061232,
"pic":"https://img.alicdn.com/bao/uploaded/i4/2150908574/O1CN01O3Akm82DCwTChbTXg_!!2150908574.jpg",
"title":"Apple/苹果 iPhone XR iphone xs max手机双卡国行原装4G xr苹果x",
"price":"6000",
"promotion_price":"2009",
"sales":1973,
"loc":"广东 深圳",
"seller_id":2150908574,
"seller_nick":"实惠馆超市",
"shop_title":"新魔方数码",
"user_type":0,
"detail_url":"https://item.taobao.com/item.htm?id=619354061232",
"delivery_fee":"0.00"
}
"item":[...]
Method:
private void taobaoSearch(){
TaobaoInterface retrofitInterface = RetrofitInstance.getRetrofitInstanceTaobao().create(TaobaoInterface.class);
Call<TaobaoModel> listCall = retrofitInterface.getTaobao("item_search", "40","default", "iphone","taobao-api.p.rapidapi.com", "//apikey hidden");
listCall.enqueue(new Callback<TaobaoModel>() {
#Override
public void onResponse(Call<TaobaoModel> call, Response<TaobaoModel> response) {
//not sure what to do here
}
#Override
public void onFailure(Call<TaobaoModel> call, Throwable t) {
System.out.println("FAILED");
System.out.println(call);
t.printStackTrace();
}
});
}
TaobaoModel:
public class TaobaoModel {
#SerializedName("result")
private Result result;
public Result getResult() {
return result;
}
public void setResult(Result result) {
this.result = result;
}
}
Result:
public class Result {
#SerializedName("status")
private Status status;
#SerializedName("q")
private String q;
#SerializedName("page")
private String page;
#SerializedName("page_size")
private String page_size;
#SerializedName("total_results")
private int total_results;
#SerializedName("tmall")
private String tmall;
#SerializedName("sort")
private String sort;
#SerializedName("free_shiping")
private String free_shiping;
#SerializedName("ip")
private String ip;
#SerializedName("item")
private ArrayList<TaobaoItems> item;
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public String getQ() {
return q;
}
public void setQ(String q) {
this.q = q;
}
public String getPage() {
return page;
}
public void setPage(String page) {
this.page = page;
}
public String getPage_size() {
return page_size;
}
public void setPage_size(String page_size) {
this.page_size = page_size;
}
public int getTotal_results() {
return total_results;
}
public void setTotal_results(int total_results) {
this.total_results = total_results;
}
public String getTmall() {
return tmall;
}
public void setTmall(String tmall) {
this.tmall = tmall;
}
public String getSort() {
return sort;
}
public void setSort(String sort) {
this.sort = sort;
}
public String getFree_shiping() {
return free_shiping;
}
public void setFree_shiping(String free_shiping) {
this.free_shiping = free_shiping;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public ArrayList<TaobaoItems> getItem() {
return item;
}
public void setItem(ArrayList<TaobaoItems> item) {
this.item = item;
}
}
TaobaoItems
public class TaobaoItems {
#SerializedName("num_iid")
private long num_iid;
#SerializedName("pic")
private String pic;
#SerializedName("title")
private String title;
#SerializedName("price")
private String price;
#SerializedName("promotion_price")
private String promotion_price;
#SerializedName("sales")
private int sales;
#SerializedName("loc")
private String loc;
#SerializedName("seller_id")
private long seller_id;
#SerializedName("seller_nick")
private String seller_nick;
#SerializedName("shop_title")
private String shop_title;
#SerializedName("user_type")
private int user_type;
#SerializedName("detail_url")
private String detail_url;
#SerializedName("delivery_fee")
private String delivery_fee;
public TaobaoItems(String title, String price, String pic, String detail_url) {
this.pic = pic;
this.title = title;
this.price = price;
this.detail_url = detail_url;
}
public long getNum_iid() {
return num_iid;
}
public void setNum_iid(long num_iid) {
this.num_iid = num_iid;
}
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getPromotion_price() {
return promotion_price;
}
public void setPromotion_price(String promotion_price) {
this.promotion_price = promotion_price;
}
public int getSales() {
return sales;
}
public void setSales(int sales) {
this.sales = sales;
}
public String getLoc() {
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
public long getSeller_id() {
return seller_id;
}
public void setSeller_id(long seller_id) {
this.seller_id = seller_id;
}
public String getSeller_nick() {
return seller_nick;
}
public void setSeller_nick(String seller_nick) {
this.seller_nick = seller_nick;
}
public String getShop_title() {
return shop_title;
}
public void setShop_title(String shop_title) {
this.shop_title = shop_title;
}
public int getUser_type() {
return user_type;
}
public void setUser_type(int user_type) {
this.user_type = user_type;
}
public String getDetail_url() {
return detail_url;
}
public void setDetail_url(String detail_url) {
this.detail_url = detail_url;
}
public String getDelivery_fee() {
return delivery_fee;
}
public void setDelivery_fee(String delivery_fee) {
this.delivery_fee = delivery_fee;
}
}
Status:
public class Status {
#SerializedName("msg")
private String msg;
#SerializedName("code")
private int code;
#SerializedName("action")
private int action;
#SerializedName("execution_time")
private String execution_time;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public int getAction() {
return action;
}
public void setAction(int action) {
this.action = action;
}
public String getExecution_time() {
return execution_time;
}
public void setExecution_time(String execution_time) {
this.execution_time = execution_time;
}
}
My intention is to get the JSON Array item and display title,price,pic,detail_url from it. I found out how to display it one at a time so far, but couldn't find how to iterate the JSON object so that I can display the data in a listview. Please help, I am new to this and I've been stuck for quite awhile now. If you want to see my interface, retrofit instance etc just let me know.
private void taobaoSearch(){
TaobaoInterface retrofitInterface = RetrofitInstance.getRetrofitInstanceTaobao().create(TaobaoInterface.class);
Call<TaobaoModel> listCall = retrofitInterface.getTaobao("item_search", "40","default", "iphone","taobao-api.p.rapidapi.com", "//apikey hidden");
listCall.enqueue(new Callback<TaobaoModel>() {
#Override
public void onResponse(Call<TaobaoModel> call, Response<TaobaoModel> response) {
List<Result> retro=response.body().getitems();
generateDataList(retro);
}
#Override
public void onFailure(Call<TaobaoModel> call, Throwable t) {
System.out.println("FAILED");
System.out.println(call);
t.printStackTrace();
}
});
}
/*Method to generate List of data using RecyclerView with custom adapter*/
private void generateDataList(List<Result> dataList) {
recyclerView = findViewById(R.id.customRecycler);
adapter = new CustomAdapter(this,dataList);
recyclerView.setAdapter(adapter);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
}

Android Nested Objects and Retrofit2

I am reading a JSON like this:
{
"matches": [{
"id": 246119,
"utcDate": "2018-08-17T18:15:00Z",
"status": "FINISHED",
"homeTeam": {
"id": 298,
"name": "Girona FC"
},
"awayTeam": {
"id": 250,
"name": "Real Valladolid CF"
},
"score": {
"winner": "DRAW",
"duration": "REGULAR"
}
}]
}
I must say that the JSON is valid. I am consuming this JSON through an API. I can correctly read the properties "id", "utc" and "status", but I could not with "score", "awayTeam" and "homeTeam". I don't really know how to work those properties. I'd like to handle each propertie of score, awayTeam, and homeTeam individually, for example, I want to get just the name of awayTeam and homeTeam and the 2 properties of score.
This, is my code:
MainActivity
public class MainActivity extends AppCompatActivity {
private Retrofit retrofit;
private static final String TAG = "Football";
private RecyclerView recyclerView;
private ListaPartidosAdapter listaPartidosAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
listaPartidosAdapter = new ListaPartidosAdapter(this);
recyclerView.setAdapter(listaPartidosAdapter);
recyclerView.setHasFixedSize(true);
final LinearLayoutManager layoutManager = new LinearLayoutManager(this, VERTICAL, true);
recyclerView.setLayoutManager(layoutManager);
retrofit = new Retrofit.Builder()
.baseUrl("http://api.football-data.org/v2/")
.addConverterFactory(GsonConverterFactory.create())
.build();
obtenerDatos();
}
private void obtenerDatos() {
footballdataService service = retrofit.create(footballdataService.class);
Call<PartidosRespuesta> partidosRespuestaCall = service.obtenerlistaPartidos();
partidosRespuestaCall.enqueue(new Callback<PartidosRespuesta>() {
#Override
public void onResponse(Call<PartidosRespuesta> call, Response<PartidosRespuesta> response) {
if(response.isSuccessful()) {
PartidosRespuesta partidosRespuesta = response.body();
ArrayList<Partido> listaPartidos = partidosRespuesta.getMatches();
listaPartidosAdapter.adicionarListaPartidos(listaPartidos);
}
else {
Log.e(TAG, "onResponse: " + response.errorBody());
}
}
#Override
public void onFailure(Call<PartidosRespuesta> call, Throwable t) {
Log.e(TAG, "onFailure: " + t.getMessage());
}
});
}
}
Now this is my interface. footballdataService
public interface footballdataService {
#GET("competitions/2014/matches")
Call<PartidosRespuesta> obtenerlistaPartidos();
}
This is PartidosRespuestas class
public class PartidosRespuesta {
private ArrayList<Partido> matches;
public ArrayList<Partido> getMatches() {
return matches;
}
public void setMatches(ArrayList<Partido> matches) {
this.matches = matches;
}
}
This, is the adapter.
public class ListaPartidosAdapter extends RecyclerView.Adapter<ListaPartidosAdapter.ViewHolder> {
private static final String TAG = "Football_Adapter";
private ArrayList<Partido> dataset;
private Context context;
public ListaPartidosAdapter(Context context) {
this.context = context;
dataset = new ArrayList<Partido>();
}
#Override
public ListaPartidosAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_partidos, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ListaPartidosAdapter.ViewHolder holder, int position) {
Partido p = dataset.get(position);
holder.status.setText(p.getId());
}
#Override
public int getItemCount() {
return dataset.size();
}
public void adicionarListaPartidos(ArrayList<Partido> listaPartidos){
dataset.addAll(listaPartidos);
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView status;
public ViewHolder(View itemView) {
super(itemView);
status = (TextView) itemView.findViewById(R.id.status);
}
}
}
And this.., is Partido class
public class Partido {
private String id;
private String utcDate;
private String status;
private EquipoCasa homeTeam;
private EquipoVisita AwayTeam;
private Puntaje score;
public String getId() {
return id;
}
public String getUtcDate() {
return utcDate;
}
public String getStatus() {
return status;
}
public EquipoCasa getHomeTeam() {
return homeTeam;
}
public EquipoVisita getAwayTeam() {
return AwayTeam;
}
public Puntaje getScore() {
return score;
}
public void setId(String id) {
this.id = id;
}
public void setUtcDate(String utcDate) {
this.utcDate = utcDate;
}
public void setStatus(String status) {
this.status = status;
}
public void setHomeTeam(EquipoCasa homeTeam) {
this.homeTeam = homeTeam;
}
public void setAwayTeam(EquipoVisita awayTeam) {
AwayTeam = awayTeam;
}
public void setScore(Puntaje score) {
this.score = score;
}
public class EquipoCasa {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class EquipoVisita {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Puntaje {
private String winner;
private String duration;
public String getWinner() {
return winner;
}
public void setWinner(String winner) {
this.winner = winner;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
}
}
POJO classes of your code should this:
AwayTeam.java
//AwayTeam
public class AwayTeam {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("name")
#Expose
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
PartidosRespuesta.java
//Object response
public class PartidosRespuesta {
#SerializedName("matches")
#Expose
private List<Match> matches = null;
public List<Match> getMatches() {
return matches;
}
public void setMatches(List<Match> matches) {
this.matches = matches;
}
}
HomeTeam.java
//HomeTeam
public class HomeTeam {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("name")
#Expose
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Score.java
//Score
public class Score {
#SerializedName("winner")
#Expose
private String winner;
#SerializedName("duration")
#Expose
private String duration;
public String getWinner() {
return winner;
}
public void setWinner(String winner) {
this.winner = winner;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
}
Edit:
#Override
public void onBindViewHolder(ListaPartidosAdapter.ViewHolder holder, int position) {
Partido p = dataset.get(position);
HomeTeam homeTeam = p.getHomeTeam();
String nameHomeTeam = homeTeam.getName();
}
And tool convert json to java code: http://www.jsonschema2pojo.org/
try
public class Puntaje {
public String winner;
public String duration;
}
It's seems like you've problems with your models. Use this link to convert your json to java object.

Realm in android

I want to use two class for database.
here is my source.
public class UserInfo extends RealmObject {
private String user_email;
private String nick_name;
private String expected_date;
private boolean initial_autho;
private int resultDay;
public int getResultDay() {
return resultDay;
}
public void setResultDay(int resultDay) {
this.resultDay = resultDay;
}
public String getUser_email() {
return user_email;
}
public void setUser_email(String user_email) {
this.user_email = user_email;
}
public String getNick_name() {
return nick_name;
}
public void setNick_name(String nick_name) {
this.nick_name = nick_name;
}
public String getExpected_date() {
return expected_date;
}
public void setExpected_date(String expected_date) {
this.expected_date = expected_date;
}
public boolean getInitial_autho() {
return initial_autho;
}
public void setInitial_autho(boolean initial_autho) {
this.initial_autho = initial_autho;
}
}
public class Calendar extends Realmobject {
private long millis;
private String note; // 노트
private String mail; // who
private int image; // image resource
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public long getTime() {
return millis;
}
public String getNote() {
return note;
}
public int getImage() {
return image;
}
public void setDate(long time) {
this.millis = time;
}
public void setNote(String note) {
this.note = note;
}
public void setImage(int image) {
this.image = image;
}
}
How do I use these things in Activity?
I don't know exactly and I much appreciate if you guys could tell about that more specifically as much as you can.

Android Json parsing with GSON?

I am quite familiar with Json parsing with Gson. I have done Json parsing using Gson but recently i have multiple json objects with response, i am getting little bit stuck with parsing, here is my code,can anyone help me to solve my problem,that where i am doing wrong.
Thanks in advance
Here is my json response :-
Json response
Here is my POGO class of parsing :-
Style Profile.java
public class StyleProfile implements Parcelable {
#SerializedName("user_name")
#Expose
private String user_name;
#SerializedName("user_picture")
#Expose
private String user_picture;
#SerializedName("user_attr")
#Expose
private UserAttrEntity user_attr;
#SerializedName("user_attributes")
#Expose
private UserAttributes userAttributes;
#SerializedName("style_attr")
#Expose
private StyleAttr style_attr;
private StyleAttrEntity style_attrEntity;
private UserAttributesEntity user_attributes;
private String user_style;
#SerializedName("user_background_image")
#Expose
private String userBackgroundImage;
#SerializedName("user_style_message")
#Expose
private String userStyleMessage;
private String user_style_message;
private List<String> style_message;
public StyleProfile() {
}
protected StyleProfile(Parcel in)
{
user_name = in.readString();
user_picture = in.readString();
user_style = in.readString();
// style_message = in.readString();
}
public static final Creator<StyleProfile> CREATOR = new Creator<StyleProfile>() {
#Override
public StyleProfile createFromParcel(Parcel in) {
return new StyleProfile(in);
}
#Override
public StyleProfile[] newArray(int size) {
return new StyleProfile[size];
}
};
public StyleAttr getStyle_attr() {
return style_attr;
}
public void setStyle_attr(StyleAttr style_attr) {
this.style_attr = style_attr;
}
public String getName() {
return user_name;
}
public void setName(String name) {
this.user_name = name;
}
public String getImage() {
return user_picture;
}
public void setImage(String image) {
this.user_picture = image;
}
public UserAttrEntity getUser_attr() {
return user_attr;
}
public void setUser_attributes(UserAttributesEntity user_attributes) {
this.user_attributes = user_attributes;
}
public void setUser_style(String user_style) {
this.user_style = user_style;
}
public String getUser_style() {
return user_style;
}
public List<String> getStyle_message() {
return style_message;
}
public void setStyle_message(List<String> style_message) {
this.style_message = style_message;
}
public String getStyleMessageAsString() {
return TextUtils.join(". ", style_message);
}
public void setUser_style_message(String user_style_message) {
this.user_style_message = user_style_message;
}
public String getUser_style_message() {
return user_style_message;
}
public UserAttributesEntity getUser_attributes() {
return user_attributes;
}
public void setUser_attr(UserAttrEntity user_attr) {
this.user_attr = user_attr;
}
public UserAttributes getUserAttr() {
return userAttributes;
}
public void setUserAttr(UserAttributes userAttr) {
this.userAttributes = userAttr;
}
public UserAttributes getUserAttributes() {
return userAttributes;
}
public void setUserAttributes(UserAttributes userAttributes) {
this.userAttributes = userAttributes;
}
public String getUserStyle() {
return user_style;
}
public void setUserStyle(String userStyle) {
this.user_style = userStyle;
}
public String getUserBackgroundImage() {
return userBackgroundImage;
}
public void setUserBackgroundImage(String userBackgroundImage) {
this.userBackgroundImage = userBackgroundImage;
}
public String getUserStyleMessage() {
return userStyleMessage;
}
public void setUserStyleMessage(String userStyleMessage) {
this.userStyleMessage = userStyleMessage;
}
#Override
public int describeContents() {
return 0;
}
public StyleAttrEntity getStyle_attrEntity() {
return style_attrEntity;
}
public static Creator<StyleProfile> getCREATOR() {
return CREATOR;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(user_name);
dest.writeString(user_picture);
dest.writeParcelable(user_attr, flags);
dest.writeParcelable(style_attr, flags);
dest.writeString(user_style);
}
public void setStyle_attrEntity(StyleAttrEntity style_attrEntity) {
this.style_attrEntity = style_attrEntity;
}
public static class StyleAttr implements Parcelable {
#SerializedName("Edgy")
#Expose
private Integer edgy;
#SerializedName("Feminine")
#Expose
private Integer feminine;
#SerializedName("Fashion Forward")
#Expose
private Integer fashionForward;
#SerializedName("Classic")
#Expose
private Integer classic;
#SerializedName("Casual")
#Expose
private Integer casual;
#SerializedName("Bohemian")
#Expose
private Integer bohemian;
protected StyleAttr(Parcel in) {
edgy = in.readInt();
casual = in.readInt();
classic = in.readInt();
edgy = in.readInt();
fashionForward = in.readInt();
feminine = in.readInt();
}
public static final Creator<StyleAttr> CREATOR = new Creator<StyleAttr>() {
#Override
public StyleAttr createFromParcel(Parcel in) {
return new StyleAttr(in);
}
#Override
public StyleAttr[] newArray(int size) {
return new StyleAttr[size];
}
};
public void setBohemian(int Bohemian) {
this.bohemian = Bohemian;
}
public void setCasual(int Casual) {
this.casual = Casual;
}
public void setClassic(int Classic) {
this.classic = Classic;
}
public void setEdgy(int Edgy) {
this.edgy = Edgy;
}
public void setFashionForward(int FashionForward) {
this.fashionForward = FashionForward;
}
public void setFeminine(int Feminine) {
this.feminine = Feminine;
}
public int getBohemian() {
return bohemian;
}
public int getCasual() {
return casual;
}
public int getClassic() {
return classic;
}
public int getEdgy() {
return edgy;
}
public int getFashionForward() {
return fashionForward;
}
public int getFeminine() {
return feminine;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(bohemian);
dest.writeInt(casual);
dest.writeInt(classic);
dest.writeInt(edgy);
dest.writeInt(fashionForward);
dest.writeInt(feminine);
}
}
}
UserAttrEntity.java
public class UserAttrEntity implements Parcelable {
#SerializedName("Size")
private String Size = "";
#SerializedName("Shape")
private String Shape = "";
#SerializedName("Bottoms Size")
private String Bottoms_Size = "";
#SerializedName("Height")
private String Height = "";
#SerializedName("Shoes Size")
private String Shoes_Size = "";
#SerializedName("Complexion")
private String Face_Color = "";
#SerializedName("Face Shape")
private String Face_Shape = "";
public UserAttrEntity() {
}
protected UserAttrEntity(Parcel in) {
Shape = in.readString();
Size = in.readString();
Bottoms_Size = in.readString();
Height = in.readString();
Shoes_Size = in.readString();
Face_Color = in.readString();
Face_Shape = in.readString();
}
public static final Creator<UserAttrEntity> CREATOR = new Creator<UserAttrEntity>() {
#Override
public UserAttrEntity createFromParcel(Parcel in) {
return new UserAttrEntity(in);
}
#Override
public UserAttrEntity[] newArray(int size) {
return new UserAttrEntity[size];
}
};
public void setShape(String Shape) {
this.Shape = Shape;
}
public void setSize(String Size) {
this.Size = Size.replace("\n", " ");
}
public void setBottoms_Size(String Bottoms_Size) {
this.Bottoms_Size = Bottoms_Size + " Inch";
}
public void setHeight(String Height) {
this.Height = Height;
}
public void setShoes_Size(String Shoes_Size) {
this.Shoes_Size = Shoes_Size;
}
public void setFace_Color(String Face_Color) {
this.Face_Color = Face_Color;
}
public void setFace_Shape(String Face_Shape) {
this.Face_Shape = Face_Shape;
}
public String getShape() {
return Shape;
}
public String getSize() {
return Size;
}
public String getBottoms_Size() {
return Bottoms_Size;
}
public String getHeight() {
return Height;
}
public String getShoes_Size() {
return Shoes_Size;
}
public String getFace_Color() {
return Face_Color;
}
public String getFace_Shape() {
return Face_Shape;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(Shape);
dest.writeString(Size);
dest.writeString(Bottoms_Size);
dest.writeString(Height);
dest.writeString(Shoes_Size);
dest.writeString(Face_Color);
dest.writeString(Face_Shape);
}
}
User AttributesEntity.java
public class UserAttributes {
#SerializedName("Size")
#Expose
private Size size;
#SerializedName("Shape")
#Expose
private Shape shape;
#SerializedName("Bottoms Size")
#Expose
private BottomsSize bottomsSize;
#SerializedName("Height")
#Expose
private Height height;
#SerializedName("Shoes Size")
#Expose
private ShoesSize shoesSize;
#SerializedName("Complexion")
#Expose
private Complexion complexion;
#SerializedName("Face Shape")
#Expose
private FaceShape faceShape;
public Size getSize() {
return size;
}
public void setSize(Size size) {
this.size = size;
}
public Shape getShape() {
return shape;
}
public void setShape(Shape shape) {
this.shape = shape;
}
public BottomsSize getBottomsSize() {
return bottomsSize;
}
public void setBottomsSize(BottomsSize bottomsSize) {
this.bottomsSize = bottomsSize;
}
public Height getHeight() {
return height;
}
public void setHeight(Height height) {
this.height = height;
}
public ShoesSize getShoesSize() {
return shoesSize;
}
public void setShoesSize(ShoesSize shoesSize) {
this.shoesSize = shoesSize;
}
public Complexion getComplexion() {
return complexion;
}
public void setComplexion(Complexion complexion) {
this.complexion = complexion;
}
public FaceShape getFaceShape() {
return faceShape;
}
public void setFaceShape(FaceShape faceShape) {
this.faceShape = faceShape;
}
}
Style Profile.java
Here i am using it like this
Profile profile = gson.fromJson(obj.toString(), Profile.class);
Log.e("", "profile.getStatus() " + profile.getStatus());
mReceiver.onResponse(profile, tag);
Try this way
//Main data
public class MainData{
#SerializedName("status")
#Expose
private String status;
#SerializedName("data")
#Expose
private Data data;
}
//Data
public class Data {
#SerializedName("user_name")
#Expose
private String userName;
#SerializedName("user_picture")
#Expose
private String userPicture;
#SerializedName("user_attr")
#Expose
private UserAttr userAttr;
#SerializedName("user_attributes")
#Expose
private UserAttributes userAttributes;
#SerializedName("style_attr")
#Expose
private StyleAttr styleAttr;
#SerializedName("user_style")
#Expose
private String userStyle;
#SerializedName("user_background_image")
#Expose
private String userBackgroundImage;
#SerializedName("user_style_message")
#Expose
private String userStyleMessage;
}
//user_attr
public class UserAttr {
#SerializedName("user_attr")
private Map<String, String> userAttributes;
public Map<String, String> getUserAttributes() {
return userAttributes;
}
public void setUserAttributes(Map<String, String> userattributes) {
this.userAttributes= userattributes;
}
}
//user_attributes
public class UserAttributes {
#SerializedName("user_attributes")
private Map<String, CommonUserAttributes> userAttributes;
public Map<String, CommonUserAttributes> getUserAttributes() {
return userAttributes;
}
public void setUserAttributes(Map<String, CommonUserAttributes> userattributes) {
this.userAttributes = userattributes;
}
}
//StyleAttr
public class StyleAttr {
#SerializedName("style_attr")
private Map<String, Integer> styleAttributes;
public Map<String, Integer> getStyleAttributes() {
return styleAttributes;
}
public void setStyleAttributes(Map<String, Integer> styleAttributes) {
this.styleAttributes = styleAttributes;
}
}
//CommonUserAttributes
public class CommonUserAttributes {
#SerializedName("user_attr")
private String value;
#SerializedName("que_id")
private String bottmque_id;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getBottmque_id() {
return bottmque_id;
}
public void setBottmque_id(String bottmque_id) {
this.bottmque_id = bottmque_id;
}
}
put your get,set method yourself.

Default Constructor issue while using Jackson Parser

My model getter setter class looks like this:-
#JsonIgnoreProperties(ignoreUnknown = true)
public class CuratedOffers {
public CuratedOffers() {
}
#JsonProperty("response")
private String response;
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
#JsonProperty("data")
private Data mData;
public Data getmData() {
return mData;
}
public void setmData(Data mData) {
this.mData = mData;
}
#JsonIgnoreProperties(ignoreUnknown = true)
public class Data{
#JsonProperty("vendors")
private List<Vendor> vendorList;
public List<Vendor> getVendorList() {
return vendorList;
}
public void setVendorList(List<Vendor> vendorList) {
this.vendorList = vendorList;
}
}
#JsonIgnoreProperties(ignoreUnknown = true)
public static class Vendor {
#JsonProperty("id")
private String Id;
public String getId() {
return Id;
}
public void setId(String id) {
Id = id;
}
#JsonProperty("name")
private String venName;
public String getVenName() {
return venName;
}
public void setVenName(String venName) {
this.venName = venName;
}
#JsonProperty("image")
private String image;
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
#JsonProperty("logo")
private String logo;
public String getLogo() {
return logo;
}
public void setLogo(String logo) {
this.logo = logo;
}
#JsonProperty("offers")
private String offers;
public String getOffers() {
return offers;
}
public void setOffers(String offers) {
this.offers = offers;
}
#JsonProperty("description")
private String offer_description;
public void setOffer_description(String offer_description) {
this.offer_description = offer_description;
}
public String getOffer_description() {
return offer_description;
}
}
}
And i using Jackson while compiling through gradle ie:-
compile 'com.fasterxml.jackson.core:jackson-databind:2.4.2'
compile 'com.fasterxml.jackson.core:jackson-annotations:2.4.2'
compile 'com.fasterxml.jackson.core:jackson-core:2.4.2'
After compiling i keep getting this error in my stacktrace
com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class com.yoy.CuratedOffers$Data]: can not instantiate from JSON object (need to add/enable type information?)
Searched SO without any suitable answers.Help would be appreciated!!
As suggested by #vilpel89 i had forgot to declare a static nested class inside CuratedOffers class.Now my updated class is:-
#JsonIgnoreProperties(ignoreUnknown = true)
public class CuratedOffers {
public CuratedOffers() {
}
#JsonProperty("response")
private String response;
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
#JsonProperty("data")
private Data mData;
public Data getmData() {
return mData;
}
public void setmData(Data mData) {
this.mData = mData;
}
#JsonIgnoreProperties(ignoreUnknown = true)
public static class Data{
public Data() {
}
#JsonProperty("vendors")
private List<Vendor> vendorList;
public List<Vendor> getVendorList() {
return vendorList;
}
public void setVendorList(List<Vendor> vendorList) {
this.vendorList = vendorList;
}
}
#JsonIgnoreProperties(ignoreUnknown = true)
public static class Vendor {
public Vendor() {
}
#JsonProperty("id")
private String Id;
public String getId() {
return Id;
}
public void setId(String id) {
Id = id;
}
#JsonProperty("name")
private String venName;
public String getVenName() {
return venName;
}
public void setVenName(String venName) {
this.venName = venName;
}
#JsonProperty("image")
private String image;
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
#JsonProperty("logo")
private String logo;
public String getLogo() {
return logo;
}
public void setLogo(String logo) {
this.logo = logo;
}
#JsonProperty("offers")
private String offers;
public String getOffers() {
return offers;
}
public void setOffers(String offers) {
this.offers = offers;
}
#JsonProperty("description")
private String offer_description;
public void setOffer_description(String offer_description) {
this.offer_description = offer_description;
}
public String getOffer_description() {
return offer_description;
}
}
}
Added a static constructor to my Data class as well as Vendor Class and also added default constructors to it.Now it's working like a charm!Hope it might help someone someday!

Categories

Resources