Custom type in GreenDao with POJO class

a 夏天 提交于 2019-12-25 16:54:14

问题


This is my sample JSON:

{  
   "open":true,
   "total_products":100,
   "product":[  
      {  
         "p_id":1,
         "price":"5.00",
         "name":"blah one"
      },
      {  
         "p_id":2,
         "price":"15.00",
         "name":"blah two"
      },
...
    ]
}

This is my POJO class:

@Entity(nameInDb = "products")
public class ProductsPOJO {

    @SerializedName("open")
    @Property(nameInDb = "open")
    private boolean open;

    @SerializedName("total_products")
    @Property(nameInDb = "total_products")
    private Long total_products;

    @Convert(converter = ProductConverter.class, columnType = String.class)
    @SerializedName("product")
    @Property(nameInDb = "product")
    private Product product;

    public static class productConverter implements PropertyConverter<Product, String> {
        //What shoudl I write in convert part?!
        @Override
        public Product convertToEntityProperty(String databaseValue) {
            if (databaseValue == null) {
                return null;
            }
            for (Product p : Product.values()) {
                if (p.id == databaseValue) {
                    return p;
                }
            }
            return Product.DEFAULT;
        }

        @Override
        public String convertToDatabaseValue(Product entityProperty) {
            return entityProperty == null ? null : entityProperty.;
        }
        //
        /*@Override
        public Product convertToEntityProperty(String databaseValue) {
        return Product.valueOf(databaseValue);
        }

        @Override
        public String convertToDatabaseValue(Product entityProperty) {
        return entityProperty.name();
        }*/
    }

    public static class Product{
        @Id
        @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
    }

    public Product getProduct() {
        return product;
    }

    public void setProduct(Product data) {
        this.product = product;
    }

    //open & total_products Getters & Setters
}

But I don't know what should I write for productConverter.
In other hand, fields in Product class have multiple types. String and Integer.
I read these: https://github.com/greenrobot/greenDAO/blob/V3.1.1/examples/DaoExample/src/main/java/org/greenrobot/greendao/example/Note.java#L26-L27

http://greenrobot.org/greendao/documentation/custom-types/


回答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.




回答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 ]



来源:https://stackoverflow.com/questions/44082952/custom-type-in-greendao-with-pojo-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!