使用GSON将嵌套的JSON数组解析为数组

时间:2014-12-19 11:18:25

标签: java json gson

我需要解析以下Json

[
    "foo",
    [
        "foot mercato",
        "football",
        "foot center",
        "foorzik",
        "footao"
    ]
]

在java中使用 Gson

我真的对Array中的值感兴趣: 到目前为止,我尝试过:

String jsonStr = "[" + "\"foo\"," + " [" + "  \"foot mercato\"," + "  \"football\"," + "  \"foot center\"," +
                "  \"foorzik\"," + "  \"footao\"" + " ]" + "]";

JsonParser parser = new JsonParser();
JsonArray array = parser.parse(jsonStr).getAsJsonArray();

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

获得数组后,可以迭代它的所有元素。

for(JsonElement e : array) {
    System.out.println(e);
}

将输出

"foo"
["foot mercato","football","foot center","foorzik","footao"]

如果您只想要嵌套数组中的值,则可以执行以下操作:

JsonArray nestedArray = parser.parse(jsonStr).getAsJsonArray().get(1).getAsJsonArray();
for(JsonElement e : nestedArray) {
    System.out.println(e);
}

将输出

"foot mercato"
"football"
"foot center"
"foorzik"
"footao"

答案 1 :(得分:1)

这可能有所帮助:

String jsonStr = "[" + "\"foo\"," + " [" + "  \"foot mercato\"," + "  \"football\"," + "  \"foot center\","
                + "  \"foorzik\"," + "  \"footao\"" + " ]" + "]";

        Gson gson = new Gson();
        ArrayList<Object> dest = new ArrayList<Object>();
        dest = gson.fromJson(jsonStr, dest.getClass());

        for (Object e : dest) {
            System.out.println("T:" + e.getClass().getCanonicalName());
            if (e instanceof String) {
                System.out.println(e);
            } else if (e instanceof ArrayList) {
                for (String ele : (ArrayList<String>) e) {
                    System.out.println(ele);
                }
            }
        }

将生成:

T:java.lang.String中

FOO

T:java.util.ArrayList中

foot mercato

足球

脚中心

foorzik

footao