簡體   English   中英

使用GSON將嵌套的JSON數組解析為一個數組

[英]Parsing Nested JSON array to an Array using 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();

有什么建議嗎?

獲得數組后,就可以遍歷數組的所有元素。

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"

這可能會有所幫助:

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中

腳Mercato

足球

腳中心

foorzik

footao

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM