Custom Type In GreenDao With POJO Class
Solution 1:
EDIT: :/ I also mixed up two things here, greenrobot objectbox and greendao... Sorry for that, but the answer stays the same, just replace objectbox with greendao :)
In my opinion here you mix something up with GSON and ObjectBox (GreenDao)
You Json look like a server respone. But in your database you normaly just want to save the product entities, not the answer. So it could be better to have just a ServerResultPOJO to parse your Answer with GSON like (the below code is not tested and maybe include minor errors, its just to bring you on the right path).
public class ServerResultPOJO {
@SerializedName("open")
private boolean open;
@SerializedName("total_products")
private Long total_products;
@SerializedName("product")
private List<Product> products;
}
Your Prdouct class then could be an ObjectBox (GreenDao) entity
@Entity
public static class Product{
@Id
private long id;
@Index
@SerializedName("p_id")
private Long p_id;
@SerializedName("price")
@Property(nameInDb = "price")
private String price;
@SerializedName("name")
@Property(nameInDb = "name")
private String name;
//Getters & Setters
}
[ Id would be better not to use the server id as you database entity id. Save id and a server id seperatly. There will be no confusion for autoincrementing and other stuff ]
You dont need any converters then, just some methods tho put all products from your answer to the database- Before putting a new entity you can search for the p_id to check if you need to sync to the database before putting.
So first parse your answer, then do the database actions.
If you really really want the Response as an database entity, you need a one-to-many relation. But then you can't use the same classes for entities and GSON parsing, or you work with some @transient fields, with make things much more complex.
Solution 2:
It was because of
"GSON Expected BEGIN_ARRAY but was BEGIN_OBJECT"
Should do something like this:
JsonParser parser = new JsonParser();
JsonObject rootObject = parser.parse(JSON_STRING).getAsJsonObject();
//You can get the "open" and "total_products" here too.//
JsonElement productElement = rootObject.get("product");
Gson gson = new Gson();
List<Product> productList = new ArrayList<>();
//Check if "data" element is an array or an object and parse accordingly...
if (productElement.isJsonObject()) {
//The returned list has only 1 element
Product p = gson.fromJson(productElement, Product.class);
productList.add(p);
}
else if (productElement.isJsonArray()) {
//The returned list has >1 elements
Type productListType = new TypeToken<List<Product>>() {}.getType();
productList = gson.fromJson(productElement, productListType);
}
[ Source: https://stackoverflow.com/a/16656096/421467 ]
Post a Comment for "Custom Type In GreenDao With POJO Class"