2014-12-19 188 views
1

數組我需要使用GSON解析用下列JSON解析嵌套JSON陣列使用GSON

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

在Java。

林價值觀真正感興趣的陣列: 到目前爲止,我曾嘗試:

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

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

什麼建議嗎?

回答

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

這可能會有所幫助:

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中

T:java.util.ArrayList中

腳的Mercato

足球

腳中心

foorzik

footao