提问者:小点点

Android Room编写自定义嵌套对象


好的,我已经成功地使用Rovfit library向服务器发送了GET请求,并在我的应用程序中解析了这些数据。 现在我想要存储的数据(自定义模型类,我已经创建)在房间数据库,但我有很多模型类。 那么在数据库中编写自定义对象的最佳方法是什么?我应该如何编写类型转换器? 检查我的网络响应以了解数据有多复杂:

{
  "recipes": [
    {
      "vegetarian": false,
      "vegan": false,
      "glutenFree": true,
      "dairyFree": false,
      "veryHealthy": false,
      "cheap": false,
      "veryPopular": false,
      "sustainable": false,
      "weightWatcherSmartPoints": 9,
      "gaps": "no",
      "lowFodmap": false,
      "aggregateLikes": 27,
      "spoonacularScore": 27,
      "healthScore": 2,
      "creditsText": "Foodista.com – The Cooking Encyclopedia Everyone Can Edit",
      "license": "CC BY 3.0",
      "sourceName": "Foodista",
      "pricePerServing": 168.58,
      "extendedIngredients": [
        {
          "id": 1001,
          "aisle": "Milk, Eggs, Other Dairy",
          "image": "butter-sliced.jpg",
          "consistency": "solid",
          "name": "butter",
          "original": "1 tablespoon butter",
          "originalString": "1 tablespoon butter",
          "originalName": "butter",
          "amount": 1,
          "unit": "tablespoon",
          "meta": [],
          "metaInformation": [],
          "measures": {
            "us": {
              "amount": 1,
              "unitShort": "Tbsp",
              "unitLong": "Tbsp"
            },
            "metric": {
              "amount": 1,
              "unitShort": "Tbsp",
              "unitLong": "Tbsp"
            }
          }
        },
        {
          "id": 10011268,
          "aisle": "Produce;Ethnic Foods",
          "image": "dried-porcini-mushrooms.png",
          "consistency": "solid",
          "name": "dried porcini mushrooms",
          "original": "1 cup porcini mushrooms (dried or fresh)",
          "originalString": "1 cup porcini mushrooms (dried or fresh)",
          "originalName": "porcini mushrooms (dried or fresh)",
          "amount": 1,
          "unit": "cup",
          "meta": [
            "fresh",
            "()"
          ],
          "metaInformation": [
            "fresh",
            "()"
          ],
          "measures": {
            "us": {
              "amount": 1,
              "unitShort": "cup",
              "unitLong": "cup"
            },
            "metric": {
              "amount": 236.588,
              "unitShort": "ml",
              "unitLong": "milliliters"
            }
          }
        },
        {
          "id": 1053,
          "aisle": "Milk, Eggs, Other Dairy",
          "image": "fluid-cream.jpg",
          "consistency": "liquid",
          "name": "heavy cream",
          "original": "1/2 cup heavy cream (or until desired consistency)",
          "originalString": "1/2 cup heavy cream (or until desired consistency)",
          "originalName": "heavy cream (or until desired consistency)",
          "amount": 0.5,
          "unit": "cup",
          "meta": [
            "(or until desired consistency)"
          ],
          "metaInformation": [
            "(or until desired consistency)"
          ],
          "measures": {
            "us": {
              "amount": 0.5,
              "unitShort": "cups",
              "unitLong": "cups"
            },
            "metric": {
              "amount": 118.294,
              "unitShort": "ml",
              "unitLong": "milliliters"
            }
          }
        },
        {
          "id": 1033,
          "aisle": "Cheese",
          "image": "parmesan.jpg",
          "consistency": "solid",
          "name": "parmesan cheese",
          "original": "1 cup grated Parmesan cheese (or more to taste)",
          "originalString": "1 cup grated Parmesan cheese (or more to taste)",
          "originalName": "grated Parmesan cheese (or more to taste)",
          "amount": 1,
          "unit": "cup",
          "meta": [
            "grated",
            "to taste",
            "( )"
          ],
          "metaInformation": [
            "grated",
            "to taste",
            "( )"
          ],
          "measures": {
            "us": {
              "amount": 1,
              "unitShort": "cup",
              "unitLong": "cup"
            },
            "metric": {
              "amount": 236.588,
              "unitShort": "ml",
              "unitLong": "milliliters"
            }
          }
        },
        {
          "id": 10035137,
          "aisle": "Pasta and Rice;Ethnic Foods;Baking",
          "image": "cornmeal.png",
          "consistency": "solid",
          "name": "polenta",
          "original": "1 cup polenta",
          "originalString": "1 cup polenta",
          "originalName": "polenta",
          "amount": 1,
          "unit": "cup",
          "meta": [],
          "metaInformation": [],
          "measures": {
            "us": {
              "amount": 1,
              "unitShort": "cup",
              "unitLong": "cup"
            },
            "metric": {
              "amount": 236.588,
              "unitShort": "ml",
              "unitLong": "milliliters"
            }
          }
        },
        {
          "id": 2047,
          "aisle": "Spices and Seasonings",
          "image": "salt.jpg",
          "consistency": "solid",
          "name": "salt",
          "original": "Salt to taste",
          "originalString": "Salt to taste",
          "originalName": "Salt to taste",
          "amount": 6,
          "unit": "servings",
          "meta": [
            "to taste"
          ],
          "metaInformation": [
            "to taste"
          ],
          "measures": {
            "us": {
              "amount": 6,
              "unitShort": "servings",
              "unitLong": "servings"
            },
            "metric": {
              "amount": 6,
              "unitShort": "servings",
              "unitLong": "servings"
            }
          }
        },
        {
          "id": 14412,
          "aisle": "Beverages",
          "image": "water.png",
          "consistency": "liquid",
          "name": "water",
          "original": "4 cups water",
          "originalString": "4 cups water",
          "originalName": "water",
          "amount": 4,
          "unit": "cups",
          "meta": [],
          "metaInformation": [],
          "measures": {
            "us": {
              "amount": 4,
              "unitShort": "cups",
              "unitLong": "cups"
            },
            "metric": {
              "amount": 946.352,
              "unitShort": "ml",
              "unitLong": "milliliters"
            }
          }
        }
      ],
      "id": 640677,
      "title": "Creamy Porcini Mushroom Polenta",
      "readyInMinutes": 45,
      "servings": 6,
      "sourceUrl": "http://www.foodista.com/recipe/F38KZJ88/creamy-porcini-mushroom-polenta",
      "image": "https://spoonacular.com/recipeImages/640677-556x370.jpg",
      "imageType": "jpg",
      "summary": "Creamy Porcini Mushroom Polentan is a <b>gluten free</b> side dish. This recipe makes 6 servings with <b>263 calories</b>, <b>9g of protein</b>, and <b>14g of fat</b> each. For <b>$1.69 per serving</b>, this recipe <b>covers 7%</b> of your daily requirements of vitamins and minerals. Head to the store and pick up water, porcini mushrooms, heavy cream, and a few other things to make it today. 27 people have made this recipe and would make it again. From preparation to the plate, this recipe takes approximately <b>45 minutes</b>. All things considered, we decided this recipe <b>deserves a spoonacular score of 30%</b>. This score is not so super. Try <a href=\"https://spoonacular.com/recipes/wild-mushroom-polenta-with-porcini-sauce-620778\">Wild Mushroom Polenta with Porcini Sauce</a>, <a href=\"https://spoonacular.com/recipes/creamy-polenta-mushroom-ragout-502641\">Creamy polenta & mushroom ragout</a>, and <a href=\"https://spoonacular.com/recipes/polenta-with-creamy-mushroom-sauce-695425\">Polenta with Creamy Mushroom Sauce</a> for similar recipes.",
      "cuisines": [],
      "dishTypes": [
        "side dish"
      ],
      "diets": [
        "gluten free"
      ],
      "occasions": [],
      "winePairing": {},
      "instructions": "<ol><li>In a large heavy bottomed saucepan, season water with salt and bring to a boil. Quickly whisk in the polenta until fully incorporated.</li><li>Lower the heat to a simmer, add the butter and porcini and allow the polenta to cook, stirring occasionally for about 30 minutes.</li><li>Finish by stirring in the cream and Parmesan cheese. If necessary, add salt to taste.</li></ol>",
      "analyzedInstructions": [
        {
          "name": "",
          "steps": [
            {
              "number": 1,
              "step": "In a large heavy bottomed saucepan, season water with salt and bring to a boil. Quickly whisk in the polenta until fully incorporated.Lower the heat to a simmer, add the butter and porcini and allow the polenta to cook, stirring occasionally for about 30 minutes.Finish by stirring in the cream and Parmesan cheese. If necessary, add salt to taste.",
              "ingredients": [
                {
                  "id": 1033,
                  "name": "parmesan",
                  "localizedName": "parmesan",
                  "image": "parmesan.jpg"
                },
                {
                  "id": 10035137,
                  "name": "polenta",
                  "localizedName": "polenta",
                  "image": "cornmeal.png"
                },
                {
                  "id": 1001,
                  "name": "butter",
                  "localizedName": "butter",
                  "image": "butter-sliced.jpg"
                },
                {
                  "id": 1053,
                  "name": "cream",
                  "localizedName": "cream",
                  "image": "fluid-cream.jpg"
                },
                {
                  "id": 14412,
                  "name": "water",
                  "localizedName": "water",
                  "image": "water.png"
                },
                {
                  "id": 2047,
                  "name": "salt",
                  "localizedName": "salt",
                  "image": "salt.jpg"
                }
              ],
              "equipment": [
                {
                  "id": 404669,
                  "name": "sauce pan",
                  "localizedName": "sauce pan",
                  "image": "sauce-pan.jpg"
                },
                {
                  "id": 404661,
                  "name": "whisk",
                  "localizedName": "whisk",
                  "image": "whisk.png"
                }
              ],
              "length": {
                "number": 30,
                "unit": "minutes"
              }
            }
          ]
        }
      ],
      "originalId": null,
      "spoonacularSourceUrl": "https://spoonacular.com/creamy-porcini-mushroom-polenta-640677"
    }
  ]
}

共1个答案

匿名用户

虽然没有最好的处理方法,但是除了必须为每个字段创建转换器模型之外,明智的做法是将保存的数据量限制为只保存您需要的相关信息,然后使用自定义转换器自动转换数据。

按照OP在注释中的要求,下面是一个基本示例,说明如何为列表/数组添加类型转换器(使用Gson):

扩展方法:

 fun <T> String.fromGson(classOfT: Class<T>) = Gson().fromJson(this, classOfT)

 fun Any.toGson() = Gson().toJson(this)

转换器:

 class MyConverter {
    @TypeConverter
    fun toListOfObjects(value: String?): List<Foo> {
        if (value.isNullOrEmpty()) {
            return emptyList()
        }

        val jsonArray = value.fromGson(JsonArray::class.java)

        return jsonArray.map { jsonArray -> jsonArray.fromGson(Foo::class.java) }
    }

    @TypeConverter
    fun toString(value: List<Foo>?) = value?.toGson()
}

类似的问题/答案