【问题标题】:Deserializing objects with nested ArrayLists with Gson?使用 Gson 反序列化具有嵌套 ArrayLists 的对象?
【发布时间】:2015-05-30 03:24:14
【问题描述】:

所以我在反序列化一些具有嵌套 ArrayLists 的 JSON 时遇到了一些问题,根元素反序列化正常,但其中的嵌套 ArrayList(称为 mTest)为空值。首先是有效的 JSON。

[
{
    "mRecipeName": "FirstRecipe",
    "mTest": [
        {
            "mIngredientName": "TestIngredient1",
            "mIngredientAmount": "1",
            "mUnit": "tbsp"
        },
        {
            "mIngredientName": "TestIngredient2",
            "mIngredientAmount": "2",
            "mUnit": "tbsp"
        }
    ],
    "mRecipeDescription": "Recipe1"
},
{
    "mRecipeName": "SecondRecipe",
    "mTest": [
        {
            "mIngredientName": "TestIngredient1",
            "mIngredientAmount": "1",
            "mUnit": "tbsp"
        },
        {
            "mIngredientName": "TestIngredient2",
            "mIngredientAmount": "2",
            "mUnit": "tbsp"
        }
    ],
    "mRecipeDescription": "Recipe2"
    }
]

这是配方类

public class Recipe {

    public String mRecipeName; //This values good
    public String mRecipeDescription; //This values good
    public ArrayList<Test> mTest; //This returns null
}

这是测试类

public class Test {

    public String mIngredientName;
    public float mIngredientAmount;
    public String mUnit;
}

这就是我的称呼

//Is there another way to do this? Or does this have to be done for every nested
//ArrayList? If so how?

Gson gson = new Gson();
        ArrayList<Recipe> result = gson.fromJson(json, new TypeToken<ArrayList<Recipe>>() {}.getType());

非常感谢任何回复的人!

【问题讨论】:

    标签: java json arraylist nested gson


    【解决方案1】:

    所以在又一个小时的头发撕裂后,我意识到“测试”来自 JUnit 框架,而不是我自己的测试类,哦,太痛苦了!然而,让我首先制作一个测试类的原因是它不起作用,当然现在神秘地起作用了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-05
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多