this is my first post and I'm newbie in firebase, sorry if i'm doing some stupid question. Hope you can help me.
This is my bean:
public class Fornecedor implements Comparable{
private int id;
private String nome;
private String email;
private int logo;
private Set<Produto> produtos;
private Set<Representante> representantes;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getLogo() {
return logo;
}
public void setLogo(int logo) {
this.logo = logo;
}
public Set<Produto> getProdutos() {
return produtos;
}
public void setProdutos(HashSet<Produto> produtos) {
this.produtos = produtos;
}
public Set<Representante> getRepresentantes() {
return representantes;
}
public void setRepresentantes(HashSet<Representante> representantes) {
this.representantes = representantes;
}
}
This is my firebase data structure:
{
"fornecedores" : {
"avon" : {
"email" : "contato#avon.com.br",
"logo" : "avon.jpg",
"nome" : "Avon Cosméticos",
"produtos" : {
"cremex" : true,
"perfumex" : true
},
"representantes" : {
"jao" : true,
"ze" : true
}
},
... other nodes like above ...
}
}
This is what I'm trying to do:
Firebase ref = new Firebase("https://nasuakz.firebaseio.com/fornecedores");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
System.out.println("Tem " + snapshot.getChildrenCount() + " fornecedores");
for (DataSnapshot fornecedorSnapshot : snapshot.getChildren()) {
Fornecedor fornecedor = fornecedorSnapshot.getValue(Fornecedor.class);
System.out.println(fornecedor.getNome() + " - " + fornecedor.getEmail());
}
}
}
and this is the error that happens on line 7 of above code:
Can not deserialize instance of java.util.HashSet
i know that is something wrong with mapping the json to my bean, but this works when i use parcelable, so i'm not understanding why this happen.
Your produtos and representantes are not sets, but maps. They map a String key to a Boolean value.
So you need to provide the proper mapping for them:
public class Fornecedor implements Comparable{
private int id;
private String nome;
private String email;
private int logo;
private Map<String, Boolean> produtos;
private Map<String, Boolean> representantes;
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getNome() { return nome; }
public void setNome(String nome) { this.nome = nome; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
public int getLogo() { return logo; }
public void setLogo(int logo) { this.logo = logo; }
public Map<String, Boolean> getProdutos() { return produtos; }
public Map<String, Boolean> getRepresentantes() { return representantes; }
}
You can of course add helper methods to look up the correct Produto and Representante objects. Just be sure to mark then as #JsonIgnore, so that Jackson doesn't try to serialize them.
Related
I am trying to insert realm lists to my realmdb in my first insert there is no problem but when I insert another realmList with a different class, my old values are deleted. So how can I insert a realmlist to DB? inserts are done separately.
RealmList<Product> insertedProduct = new RealmList<Product>();
RealmList<ProductSubCategory> insertedSubCategory = new RealmList<ProductSubCategory>();
RealmList<ProductMainCategory> insertedMainCategory = new RealmList<ProductMainCategory>();
... inserting to realm list firt time ...
insertRealmList(insertedProduct); //inserting to realmDB first time
insertRealmList(insertedSubCategory); //inserting to realmDB first time
insertRealmList(insertedMainCategory); //inserting to realmDB first time
first insert to realmDB
RealmList insert function
private void insertRealmList(final RealmList realmObject) {
mRealm = Realm.getDefaultInstance();
realmTask = mRealm.executeTransactionAsync(
new Realm.Transaction() {
#Override
public void execute(Realm realm) {
realm.copyToRealmOrUpdate(realmObject);
}
},
new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
Log.i(TAG, "onSuccess: successfully inserted data");
}
},
new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
Log.i(TAG, "onError: error while inserting " + "error: " + error);
}
}
);
}
... inserting to realm list second time...
insertRealmList(insertedLanguages); //insert realmDB second time
second insert to realmDB
PRODUCT MODEL
package Model;
import io.realm.RealmList;
import io.realm.RealmObject;
import io.realm.annotations.Ignore;
import io.realm.annotations.Index;
import io.realm.annotations.PrimaryKey;
public class Product extends RealmObject {
#PrimaryKey
#Index
private int ID;
#Index
private int PLU_NO;
private String PRODUCT_NAME;
private String MAIN_CATEGORY;
private String SUB_CATEGORY;
private String TYPE;
private String TUS;
private Double PRICE;
private String CALORIE;
private String COOKING_TIME;
private RealmList<String> PRODUCT_NAME_LANGUAGES;
private RealmList<String> PRODUCT_DESCRIPTION_LANGUAGES;
private String IMAGE_BASE_HORIZONTAL; //4/3
private String IMAGE_BASE_VERTICAL; //16/9
private String VIDEO_NAME; //video name
#Ignore
private int AMOUNT;
#Ignore
private int WINDOW_AMOUNT = 1;
public Product(int ID, int PLU_NO, String PRODUCT_NAME, String MAIN_CATEGORY, String SUB_CATEGORY, String TYPE, String TUS, Double PRICE, String CALORIE, String COOKING_TIME, RealmList<String> PRODUCT_NAME_LANGUAGES, RealmList<String> PRODUCT_DESCRIPTION_LANGUAGES, String IMAGE_BASE_HORIZONTAL, String IMAGE_BASE_VERTICAL, String VIDEO_NAME) {
this.ID = ID;
this.PLU_NO = PLU_NO;
this.PRODUCT_NAME = PRODUCT_NAME;
this.MAIN_CATEGORY = MAIN_CATEGORY;
this.SUB_CATEGORY = SUB_CATEGORY;
this.TYPE = TYPE;
this.TUS = TUS;
this.PRICE = PRICE;
this.CALORIE = CALORIE;
this.COOKING_TIME = COOKING_TIME;
this.PRODUCT_NAME_LANGUAGES = PRODUCT_NAME_LANGUAGES;
this.PRODUCT_DESCRIPTION_LANGUAGES = PRODUCT_DESCRIPTION_LANGUAGES;
this.IMAGE_BASE_HORIZONTAL = IMAGE_BASE_HORIZONTAL;
this.IMAGE_BASE_VERTICAL = IMAGE_BASE_VERTICAL;
this.VIDEO_NAME = VIDEO_NAME;
}
public Product() {
}
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
public int getPLU_NO() {
return PLU_NO;
}
public void setPLU_NO(int PLU_NO) {
this.PLU_NO = PLU_NO;
}
public String getPRODUCT_NAME() {
return PRODUCT_NAME;
}
public void setPRODUCT_NAME(String PRODUCT_NAME) {
this.PRODUCT_NAME = PRODUCT_NAME;
}
public String getMAIN_CATEGORY() {
return MAIN_CATEGORY;
}
public void setMAIN_CATEGORY(String MAIN_CATEGORY) {
this.MAIN_CATEGORY = MAIN_CATEGORY;
}
public String getSUB_CATEGORY() {
return SUB_CATEGORY;
}
public void setSUB_CATEGORY(String SUB_CATEGORY) {
this.SUB_CATEGORY = SUB_CATEGORY;
}
public String getTYPE() {
return TYPE;
}
public void setTYPE(String TYPE) {
this.TYPE = TYPE;
}
public String getTUS() {
return TUS;
}
public void setTUS(String TUS) {
this.TUS = TUS;
}
public Double getPRICE() {
return PRICE;
}
public void setPRICE(Double PRICE) {
this.PRICE = PRICE;
}
public String getCALORIE() {
return CALORIE;
}
public void setCALORIE(String CALORIE) {
this.CALORIE = CALORIE;
}
public String getCOOKING_TIME() {
return COOKING_TIME;
}
public void setCOOKING_TIME(String COOKING_TIME) {
this.COOKING_TIME = COOKING_TIME;
}
public RealmList<String> getPRODUCT_NAME_LANGUAGES() {
return PRODUCT_NAME_LANGUAGES;
}
public void setPRODUCT_NAME_LANGUAGES(RealmList<String> PRODUCT_NAME_LANGUAGES) {
this.PRODUCT_NAME_LANGUAGES = PRODUCT_NAME_LANGUAGES;
}
public RealmList<String> getPRODUCT_DESCRIPTION_LANGUAGES() {
return PRODUCT_DESCRIPTION_LANGUAGES;
}
public void setPRODUCT_DESCRIPTION_LANGUAGES(RealmList<String> PRODUCT_DESCRIPTION_LANGUAGES) {
this.PRODUCT_DESCRIPTION_LANGUAGES = PRODUCT_DESCRIPTION_LANGUAGES;
}
public String getIMAGE_BASE_HORIZONTAL() {
return IMAGE_BASE_HORIZONTAL;
}
public void setIMAGE_BASE_HORIZONTAL(String IMAGE_BASE_HORIZONTAL) {
this.IMAGE_BASE_HORIZONTAL = IMAGE_BASE_HORIZONTAL;
}
public String getIMAGE_BASE_VERTICAL() {
return IMAGE_BASE_VERTICAL;
}
public void setIMAGE_BASE_VERTICAL(String IMAGE_BASE_VERTICAL) {
this.IMAGE_BASE_VERTICAL = IMAGE_BASE_VERTICAL;
}
public String getVIDEO_NAME() {
return VIDEO_NAME;
}
public void setVIDEO_NAME(String VIDEO_NAME) {
this.VIDEO_NAME = VIDEO_NAME;
}
public int getAMOUNT() {
return AMOUNT;
}
public void setAMOUNT(int AMOUNT) {
this.AMOUNT = AMOUNT;
}
public int getWINDOW_AMOUNT() {
return WINDOW_AMOUNT;
}
public void setWINDOW_AMOUNT(int WINDOW_AMOUNT) {
this.WINDOW_AMOUNT = WINDOW_AMOUNT;
}
public void setDEFAULT_WINDOW_AMOUNT() {
this.WINDOW_AMOUNT = 1;
}
}
LANGUAGE MODEL
package Model;
import io.realm.RealmObject;
public class Language extends RealmObject {
#PrimaryKey
#Index
private int ID;
private String ICON;
private String NAME;
public Language(){
}
public Language(int ID, String ICON, String NAME) {
this.ID = ID;
this.ICON = ICON;
this.NAME = NAME;
}
public int getId() {
return ID;
}
public void setId(int id) {
this.ID = id;
}
public String getICON() {
return ICON;
}
public void setICON(String ICON) {
this.ICON = ICON;
}
public String getName() {
return NAME;
}
public void setName(String name) {
this.NAME = name;
}
}
Other two models are similar with product.
Please try the following method:
private <T extends RealmModel> void insertRealmList(final List<T> objects) {
try (Realm realmInstance = Realm.getDefaultInstance()) {
realmInstance.executeTransaction(realm -> {
for (T object : objects) {
realmInstance.insertOrUpdate(object);
}
});
}
}
Hope this helps!
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.
I want to get data from my localhost with retrofit library. I want to make it so that when I click the button, all TextView will set new value. For example, TextView username will change "developer" in my json file. However, when I clicked the button I guess json returned null because I can not see anything. Can you help me solve this problem?
JSON File :
{"USERS":[{"_id":"587c0346f8469d38a0ea46bf",
"username":"developer",
"name":"Akif",
"surname":"Demirezen",
"tel":"023656565",
"age":"25",
"location_id":{"_id":"587c0346f8469d38a0ea46be",
"il":"istanbul",
"ilce":"cevizlibağ"},
"__v":0}]}
Example.class :
public class Example {
#SerializedName("USERS")
#Expose
private List<USER> uSERS = null;
public List<USER> getUSERS() {
return uSERS;
}
public void setUSERS(List<USER> uSERS) {
this.uSERS = uSERS;
}
}
LocationID Class :
public class LocationId {
#SerializedName("_id")
#Expose
private String id;
#SerializedName("il")
#Expose
private String il;
#SerializedName("ilce")
#Expose
private String ilce;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getIl() {
return il;
}
public void setIl(String il) {
this.il = il;
}
public String getIlce() {
return ilce;
}
public void setIlce(String ilce) {
this.ilce = ilce;
}
}
Main Activity Class :
public class MainActivity extends AppCompatActivity {
TextView tid,tusername,tname,tsurname,tage,ttel,tlocationid;
Button butonverilerigoster;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tid = (TextView) findViewById(R.id.t_id);
tusername = (TextView) findViewById(R.id.t_username);
tname = (TextView) findViewById(R.id.t_name);
tsurname = (TextView) findViewById(R.id.t_surname);
tage = (TextView) findViewById(R.id.t_age);
ttel = (TextView) findViewById(R.id.t_tel);
tlocationid = (TextView) findViewById(R.id.t_locationid);
butonverilerigoster = (Button) findViewById(R.id.butonusergetir);
butonverilerigoster.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new Thread(new Runnable() {
public void run() {
ApiService.Factory.getInstance().getuse().enqueue(new Callback<USER>() {
#Override
public void onResponse(Call<USER> call, Response<USER> response) {
tid.setText(response.body().getId());
tusername.setText(response.body().getUsername());
tname.setText(response.body().getName());
tsurname.setText(response.body().getSurname());
tage.setText(response.body().getAge());
ttel.setText(response.body().getTel());
tlocationid.setText((CharSequence) response.body().getLocationId());
}
#Override
public void onFailure(Call<USER> call, Throwable t) {
Log.e("Failed", t.getMessage());
}
});
}
}).start();
}
});
}
}
User class :
public class USER {
#SerializedName("_id")
#Expose
private String id;
#SerializedName("username")
#Expose
private String username;
#SerializedName("name")
#Expose
private String name;
#SerializedName("surname")
#Expose
private String surname;
#SerializedName("tel")
#Expose
private String tel;
#SerializedName("age")
#Expose
private String age;
#SerializedName("location_id")
#Expose
private LocationId locationId;
#SerializedName("__v")
#Expose
private Integer v;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public LocationId getLocationId() {
return locationId;
}
public void setLocationId(LocationId locationId) {
this.locationId = locationId;
}
public Integer getV() {
return v;
}
public void setV(Integer v) {
this.v = v;
}
}
I have two classes.
Class SubCategory
public class SubCategory implements Comparable<SubCategory>{
private int scid;
private String scname;
public SubCategory(int scid, String scname) {
this.scid = scid;
this.scname = scname;
}
public int getScid() {
return scid;
}
public void setScid(int scid) {
this.scid = scid;
}
public String getScname() {
return scname;
}
public void setScname(String scname) {
this.scname = scname;
}
public int compareTo(SubCategory subCategory){
return this.getScname().compareTo(subCategory.getScname());
}
}
Class Category
public class Category implements Comparable<Category>{
private int id;
private String name;
private String image;
private int display_with;
private List<SubCategory> subcategories;
public Category(int id, String name, String image, int display_with, List<SubCategory> subcategories) {
this.id = id;
this.name = name;
this.image = image;
this.display_with = display_with;
this.subcategories = subcategories;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public int getDisplay_with() {
return display_with;
}
public void setDisplay_with(int display_with) {
this.display_with = display_with;
}
public List<SubCategory> getSubcategories() {
return subcategories;
}
public void setSubcategories(List<SubCategory> subcategories) {
this.subcategories = subcategories;
}
public int compareTo(Category category){
return this.getName().compareTo(category.getName());
}
}
This is retrofir request.
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASERESTURL)
.addConverterFactory(GsonConverterFactory.create())
.build();
I am Parsing the data with gson library in retrofit response
public void onResponse(retrofit.Response<List<Category>> response, Retrofit retrofit) {
loading.dismiss();
List<Category> categories = response.body();
Collections.sort(categories);
Utility.setCategories(categories);
}
i can sort the categories with Collections.sort(categories);
But how to sort subcategories with category??
You can do this right in setSubcategories, so everytime you set new subcategories they will get sorted:
public void setSubcategories(List<SubCategory> subcategories) {
Collections.sort(subcategories)
this.subcategories = subcategories;
}
Also you should replace this.subcategories = subcategories; with this.setSubcategories(subcategories) in your Constructor.
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!