为了学习的目的,我使用Realm和Edinburg Festival Api创建了一个Android应用程序。除了一个问题之外,它会很好。RealmObject的自定义解串器
我使用以下检索到的JSON转换为RealmObjects:
public void onResponse(final String response) {
realm.executeTransactionAsync(new Realm.Transaction(){
@Override
public void execute(Realm realm) {
// Update our realm with the results
parseImages();
realm.createOrUpdateAllFromJson(Festival.class, response);
}
}
}
这工作只有一个行业例外,图像精细。 JSON的图像部分:
"images": {
"031da8b4bad1360eddea87e8820615016878b183": {
"hash": "031da8b4bad1360eddea87e8820615016878b183",
"orientation": "landscape",
"type": "hero",
"versions": {
"large-1024": {
"height": 213,
"mime": "image/png",
"type": "large-1024",
}
"width": 1024
}
}
这里的问题是图像对象中的散列。我不知道如何处理这个问题。哈希每个节日都有所不同。是否有可能在我的RealmObject中创建一个自定义的JSON解串器?
最后的代码示例是我目前的模型:
public class Festival extends RealmObject {
@PrimaryKey
public String title;
RealmList<Image> images;
public String description_teaser;
public String description;
public String genre;
public String age_category;
public String website;
public RealmList<Performance> performances;
public int votes;
}
我知道我的PK是不是最优的,但是这还只是测试,以获得工作的图片,我需要设置PK迁移。
任何提示,欢迎,欢呼:)
更新
添加了图像模型:
public class Image extends RealmObject {
public String hash;
public String orientation;
public String type;
RealmList<Version> versions;
}
更新2
我尝试打电话realm.createOrUpdateAllFromJson前解析图像(Festival.class,回应);
private void parseImages(String jsonString) throws JSONException {
JSONArray jsonArr = new JSONArray(jsonString);
for(int i = 0; i < jsonArr.length(); i++){
JSONObject jsonObj = jsonArr.getJSONObject(i);
JSONObject images = (JSONObject)jsonObj.get("images");
Iterator<String> iter = images.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
JSONObject value = json.get(key);
realm.createOrUpdateObjectFromJson(Image.class,value);
} catch (JSONException e) {
// Something went wrong!
}
}
}
}
更新3
我创建了清理破碎的JSON我从API获得的功能。这不是很好,但它现在工作。它删除了哈希和奇怪的版本,并将它们放在一个数组中。我确信它可以更有效地写入,但我只是去这个,所以我现在可以继续我的应用程序的其余部分。看到我自己的答案。
好的 - ------ – EpicPandaForce