2016-09-06 93 views
0

我們有一個相當奇怪的JSON有效負載需要反序列化,但我不確定如何去用Java和Gson來完成它。反序列化沒有名稱的JSON對象

{ 
    "Red": { 
      "Level 1": "Specify Action", 
      "Level 2": "Action Taken", 
      "Level 3": "No Action Taken" 
    }, 
    "Orange": { 
      "Level 4": "Defeat Gannon", 
      "Level 5": "Save Princess", 
      "Level 6": "Find Triforce" 
    } 
} 

我們可以用一個HashMap反序列化的單個對象(即「紅色」和「橙色」),但我們現在正試圖佔父對象的問題,正如代碼所示,沒有任何名字可以輕鬆入侵。

+0

如何在HashMap函數中傳遞這個有效載荷(如果它沒有變量名稱的話)? – petryuno1

+0

對不起,我不清楚。我只想到我可以使用HashMap來表示「紅色」和「橙色」對象,但正如您所指出的,由於我不確定如何引用父對象,因此無法傳遞整體有效內容。 – killQuotes

+0

父母對象是什麼意思? –

回答

0

考慮到您的JSON看起來像如下:

{ 
    "Red": { 
     "Level 1": "Specify Action", 
     "Level 2": "Action Taken", 
     "Level 3": "No Action Taken" 
    }, 
    "Orange": { 
     "Level 4": "Defeat Gannon", 
     "Level 5": "Save Princess", 
     "Level 6": "Find Triforce" 
    } 
} 

我將使用HashMap的,像下面傑克遜API。我認爲類似的也可以使用GSON來完成

import com.fasterxml.jackson.core.type.TypeReference; 
import com.fasterxml.jackson.databind.ObjectMapper; 

     import java.io.IOException; 
     import java.util.HashMap; 
     import java.util.Map; 

     public class Test { 

      public static void main(String[] args) throws IOException { 

       ObjectMapper mapper = new ObjectMapper(); 
       String jsonInString = "{\n" + 
         " \"Red\": {\n" + 
         "  \"Level 1\": \"Specify Action\",\n" + 
         "  \"Level 2\": \"Action Taken\",\n" + 
         "  \"Level 3\": \"No Action Taken\"\n" + 
         " },\n" + 
         " \"Orange\": {\n" + 
         "  \"Level 4\": \"Defeat Gannon\",\n" + 
         "  \"Level 5\": \"Save Princess\",\n" + 
         "  \"Level 6\": \"Find Triforce\"\n" + 
         " }\n" + 
         "}"; 

       TypeReference< Map<String, HashMap<String, String>>> typeRef 
         = new TypeReference<Map<String, HashMap<String, String>>>() { 
       }; 

       Map<String, HashMap<String, String>> value = mapper.readValue(jsonInString, typeRef); 

       System.out.println(value); 

      } 
     }