mSapps mSapps - 2 months ago 31
Android Question

Creating common data model for greenDao and retrofit

I have json reponse from a web service which is like this

{
"id":1,
"name":"abc",
"address": {
"streetName":"cde",
"city":NY
}
}


I am using Retrofit and greenDao for my project . For both we need a data model . For retrofit only , my data model look like this

public class Example {

private Integer id;
private String name;
private Address address;

public Example() {
}

public Example(Integer id, String name, Address address) {
this.id = id;
this.name = name;
this.address = address;
}

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;
}


public Address getAddress() {
return address;
}


public void setAddress(Address address) {
this.address = address;
}

}




public class Address {

private String streetName;
private String city;

public Address() {
}

public Address(String streetName, String city) {
this.streetName = streetName;
this.city = city;
}


public String getStreetName() {
return streetName;
}


public void setStreetName(String streetName) {
this.streetName = streetName;
}


public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}

}


Which can be used for
Retrofit
, but
greenDao
has a generator , which also make data model . How can I generate Datamodel from greenDao generator project , which can be used for both retrofit and greenDao

Thanks in advance

Answer

Here is how a generator should look like:

    Schema schema = new Schema(1, <your.package.id.where.models.are.held>);

    Entity model = schema.addEntity("Model");
    model.addIdProperty();
    model.addStringProperty("name");

    Entity address = schema.addEntity("Address");
    Property addressIdProperty = address.addIdProperty().getProperty();
    address.addStringProperty("streetName");
    address.addStringProperty("city");

    model.addToOne(address, addressIdProperty).setName("address");

    DaoGenerator generator = new DaoGenerator();
    generator.generateAll(schema, "./app/src/main/java");

As you can see, the Model class contains a reference to address, by adding one-to-one relation and naming it "address".

This way any json parser like GSON can parse your objects and put them in database.