2016-01-20 79 views
0

我有一个带有对象的RealmObject类,它的实际PrimaryKey作为此对象中的字符串。但不允许将对象作为主键。从嵌套对象字段映射主键

public class Model extends RealmObject { 
    @PrimaryKey 
    private Id _id; 
    ... 
} 

public class Id extends RealmObject { 
    private String id; // the primary key for the class Model 
    ... 
} 

由于目前无法更改服务器的响应结构,我尝试了不同的方法来解决此问题。但目前为止他们还没有工作。我在Android Studio中使用“io.realm:realm-gradle-plugin:0.87.2”作为我的项目的“realm-android”插件。

1.

public class Model extends RealmObject { 
    @PrimaryKey 
    private String id; 
    private Id _id; 

    public String getId() { 
     return _id.getId(); 
    } 
    ... 
} 

2.

public class Model extends RealmObject { 
    @PrimaryKey 
    @SerializedName("_id.id") 
    private String id; 
    private Id _id; 
    ... 
} 

你将如何解决呢?只能使用Realm,还是必须使用第二个工具,如gson库?

编辑:

谢谢beeender的答案!它正在工作,但如果有人有更好的解决方案,欢迎您。

  JSONArray jsonArray = null; 
      try { 
       jsonArray = new JSONArray(total.toString()); 
       for(int i = 0; i < jsonArray.length(); i++) { 
        JSONObject jsonObject = jsonArray.getJSONObject(i); 
        String id = jsonObject.getJSONObject("_id").getString("id"); 
        jsonObject.put("id", id); 
       } 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 
+2

我想在这个特殊的情况下,你需要自己解析JSON。同样将'Id.idString'存储为'Model.idString'。 – beeender

回答

1

谢谢beeender的答案!它正在工作,但如果有人有更好的解决方案,欢迎您。

 JSONArray jsonArray = null; 
     try { 
      jsonArray = new JSONArray(total.toString()); 
      for(int i = 0; i < jsonArray.length(); i++) { 
       JSONObject jsonObject = jsonArray.getJSONObject(i); 
       String id = jsonObject.getJSONObject("_id").getString("id"); 
       jsonObject.put("id", id); 
      } 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     }