使用Gson嵌套ArrayLists反序列化对象?

时间:2015-03-26 07:19:16

标签: java json arraylist nested gson

所以我在反序列化一些嵌套了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());

非常感谢任何回复的人!

1 个答案:

答案 0 :(得分:0)

因此,经过另一个小时的头发撕裂,我意识到“测试”来自JUnit框架,而不是我自己的测试类,哦,痛苦!然而,导致我首先参加考试的原因是它不起作用,当然它现在是神秘的。