保存复杂对象时如何避免创建新模型

How to avoid creating new models when saving complex objects

我的移动设备从 API 服务器获取数据,结果集可能会变得非常复杂。这是返回结构的示例:

{
    "Home" : {
        "Person" : [
            {
                "name" : "Joe",
                "age" : 16,
                "gender" : "Male",
                "occupation" : null
            }, {
                "name" : "Jane",
                "age" : 23,
                "gender" : "Female",
                "occupation" : {
                    "position" : "Barista",
                    "years" : 4,
                    "type" : "Temporary"
                }                                
            }, {
                "name" : "Samantha",
                "age" : 7,
                "gender" : "Female",
                "occupation" : null
            }
        ]
    }
}

这只是一个对象。在这种情况下,我创建了 2 个模型:

Home & Person...但是 Person 中还有另一个对象叫做 Occupation 但我拒绝为此创建模型。

我目前保存此数据的方式是,我首先保存 Person 对象,因为我将其定义为 Home 的外部实体,然后当我保存 Home对象,我将使用 Person 的引用来持久化我的 Home 对象。

有没有办法避免做这一切?我可以只使用一个名为 Person 的模型,同时能够保留所有内部对象吗?

为可能只有一个或两个内部属性的小对象创建另一个模型是个坏主意吗?

Home & Person...BUT there is another object within Person called Occupation but I refuse to create a model for this.

为什么拒绝?这样做几乎没有惩罚,封装的好处很多。您的 JSON 将 occupation 视为 class 给定 { ... } 并且您也应该在 Java.

例如,如果您尝试将 occupation 中的字段嵌入 Personnull 职业字段将如何表示?是否会将所有字段设置为 null0?那下面的怎么表示呢?

"occupation" : {
    "position" : null,
    "years" : 0,
    "type" : null
}                                

这是最好的 hack。

Is it a bad idea to create another Model for small object that probably has only one or two properties inside?

当然不是。这是正确的做法。我会使用某种 json -> Java 转换器,然后逐个字段创建 Person 来匹配 JSON。当您使用对象并且您的表示与您的模型完全匹配时,您处理数据模型所花费的时间将得到回报。