【发布时间】:2016-11-10 19:06:31
【问题描述】:
出于学习目的,我正在使用 Realm 和 Edinburg Festival Api 创建一个 Android 应用程序。除了一个问题,一切都很顺利。
我正在使用以下方法将检索到的 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, response); 之前解析图像;
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
我创建了一个函数来清理我从 API 获得的损坏的 JSON。它不是很好,但它现在有效。它删除了哈希和奇怪的版本,并将它们都放在一个数组中。我确信它可以更有效地编写,但我会继续这样做,所以我现在可以继续我的应用程序的其余部分。请参阅我自己的答案。
【问题讨论】: