2016-11-10 38 views
0

爲了學習的目的,我使用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獲得的功能。這不是很好,但它現在工作。它刪除了哈希和奇怪的版本,並將它們放在一個數組中。我確信它可以更有效地寫入,但我只是去這個,所以我現在可以繼續我的應用程序的其餘部分。看到我自己的答案。

回答

1

我自己的臨時解決方案:

/** 
    * Function to fix the json coming from the Festival API 
    * This is a bit more complicated then it needs to be but realm does not yet support @Serializedname 
    * It removes the "large-1024" (and simllar) object and places the versions in a JSON version array 
    * Then it removes the hashes and creates and images array. The JsonArray can now be parsed normally :) 
    * 
    * @param jsonString Result string from the festival api 
    * @return JSONArray The fixed JSON in the form of a JSONArray 
    * @throws JSONException 
    */ 
    private JSONArray cleanUpJson(String jsonString) throws JSONException { 
     JSONArray json = new JSONArray(jsonString); 
     for(int i = 0; i < json.length(); i++){ 
      // We store the json Image Objects in here so we can remove the hashes 
      Map<String,JSONObject> images = new HashMap<>(); 
      JSONObject festivalJson = json.getJSONObject(i); 
      JSONObject imagesJson = (JSONObject)festivalJson.get("images"); 
      // Iterate each hash inside the images 
      Iterator<String> hashIter = imagesJson.keys(); 
      while (hashIter.hasNext()) { 
       String key = hashIter.next(); 
       try { 
        final JSONObject image = imagesJson.getJSONObject(key); 

        // Remove the version parents and map them to version 
        Map<String, JSONObject> versions = new HashMap<>(); 
        JSONObject versionsJsonObject = image.getJSONObject("versions"); 

        // Now iterate all the possible version and map add to the hashmap 
        Iterator<String> versionIter = versionsJsonObject.keys(); 
        while(versionIter.hasNext()){ 
         String currentVersion = versionIter.next(); 
         versions.put(currentVersion,versionsJsonObject.getJSONObject(currentVersion)); 
        } 

        // Use the hashmap to modify the json so we get an array of version 
        // This can't be done in the iterator because you will get concurrent error 
        image.remove("versions"); 
        Iterator hashMapIter = versions.entrySet().iterator(); 
        JSONArray versionJsonArray = new JSONArray(); 
        while(hashMapIter.hasNext()){ 
         Map.Entry pair = (Map.Entry)hashMapIter.next(); 
         versionJsonArray.put(pair.getValue()); 
        } 
        image.put("versions",versionJsonArray); 
        Log.d(LOG_TAG,image.toString()); 
       } catch (JSONException e) { 
        e.printStackTrace(); 
       } 
       images.put(key,imagesJson.getJSONObject(key)); 
      } 
      // Now let's get rid of the hashes 
      Iterator hashMapIter = images.entrySet().iterator(); 
      JSONArray imagesJsonArray = new JSONArray(); 
      while(hashMapIter.hasNext()){ 
       Map.Entry pair = (Map.Entry)hashMapIter.next(); 
       imagesJsonArray.put(pair.getValue()); 
      } 
      festivalJson.put("images", imagesJsonArray); 
     } 
     return json; 
    } 

希望它可以幫助別人:)但肯定是不整齊。

+0

好的 - ------ – EpicPandaForce

0

由於關鍵是如何動態的,這JSON(爲什麼不是這樣的數組誰設計了這個API根本不知道他們在做什麼?),you'll have to manually parse the object up to the point of the hash key

JSONObject jsonObj = new JSONObject(jsonString); 
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.toString()); 
    } catch (JSONException e) { 
     // Something went wrong! 
    } 
} 
+0

感謝您的回答。我如何將這與目前我解析json的方式結合起來?我應該@ignore圖像,然後運行此代碼添加圖像後?或者我可以以某種方式實現這realm.createOrUpdateAllFromJson內? – Juxture

+0

您需要其送入之前運行該代碼'createOrUpdateAllFromJson' –

+0

每個圖像對象應分別作爲對象被存儲,同時通過鍵解析圖像一個接一個。哈希本身也可以在對象中找到,畢竟,所以你不會丟失任何信息。 'createOrUpdateAll'需要一個數組,但這不是一個數組。 – EpicPandaForce