Search code examples
androidjsonrealmandroid-json

Is it possible to parse with JSONObject and RealmObject with the same model?


I don't want to create separate models for json and realm. I'm looking for a way to do that.

How do I handle this in a single model without creating two models?

My Json;

"story": {
   "id": 3,
   "title": "title",
   "is_new": false,
   "thumbnail": "url",
   "original": "url",
}

MyRealmObject

public class stories extends RealmObject {
    @PrimaryKey
    @Required
    private String id;
    @Required
    private String title;
    private boolean isNew;
    @Required
    private String thumbnail;
    @Required
    private String original;

    [..and getter setter..]
}

Solution

  • You can use the same model for both JSON parsing and for Realm.

    you may need to use SerializedName because field is_new won't work.

    example:

    public class Stories extend RealmObject {
    
    
    private int id;
    private String title;
    
    @SerializedName("is_new") // required
    private Boolean isNew;// use preferred name
    
    private String thumbnail;
    private String original;
    
    /* getter & setter */
    
    }
    

    Parsing

    Stories mDataClass = new Gson().fromJson("{/*whatever your json object*/}", Stories.class);