2014-11-05 72 views
0

我想創建一個JSON表示出這個Java對象。我正在使用傑克遜。Java到JSON(w /嵌套元素)

private List<Map<String, String>> Crews = new ArrayList<Map<String, String>>(); 

public Crew() { 
    Map<String, String> crew1 = new HashMap<String, String>(); 
    crew1.put("crewId", "3"); 
    crew1.put("crewName", "T.I.P."); 
    crew1.put("crewIntro", "Teamwork Is Perfect"); 
    crew1.put("crewGenre", "bboy"); 
    crew1.put("crewAsso", "TIP Studio"); 
    crew1.put("crewLeaderContact", "tip.tip.com"); 
    Crews.add(crew1); 

    Map<String, String> crew2 = new HashMap<String, String>(); 
    crew2.put("crewId", "4"); 
    crew2.put("crewName", "Pinky Chicks"); 
    crew2.put("crewIntro", "Best feminine males"); 
    crew2.put("crewGenre", "Girl's hip-hop"); 
    crew2.put("crewAsso", "JBlack Studio"); 
    crew2.put("crewLeaderContact", "[email protected]"); 
    Crews.add(crew2); 
} 

public List<Map<String, String>> getCrews() { 
    return Crews; 
} 

public void setCrews(List<Map<String, String>> crews) { 
    Crews = crews; 
} 

public static void createCrewJSON(String filePath) { 
    Crew crew = new Crew(); 
    ObjectMapper mapper = new ObjectMapper(); 
    try { 

     mapper.writeValue(new File(filePath), crew.getCrews()); 

    } catch (JsonProcessingException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     System.out.println("JSON Crew File Created"); 
    } 
} 

這是我的結果:

[ 
     { 
     "crewIntro":"Teamwork Is Perfect", 
     "crewId":"3", 
     "crewGenre":"bboy","crewName":"T.I.P.", 
     "crewLeaderContact":"tip.tip.com", 
     "crewAsso":"TIP Studio" 
     }, 
     { 
      "crewIntro":"Best feminine males", 
      "crewId":"4", 
      "crewGenre":"Girl's hip-hop", 
      "crewName":"Pinky Chicks", 
      "crewLeaderContact":"[email protected]", 
      "crewAsso":"JBlack Studio" 
     } 
    ] 

我怎麼會改變我的createCrewJSON的方法來產生這樣的:?

{ 
    "Crews": [ 
     { 
     "Crew": { 
       "crewIntro":"Teamwork Is Perfect", 
      "crewId":"3", 
      "crewGenre":"bboy","crewName":"T.I.P.", 
      "crewLeaderContact":"tip.tip.com", 
      "crewAsso":"TIP Studio" 
      } 
     }, 
     { 
     "Crew": { 
      "crewIntro":"Best feminine males", 
      "crewId":"4", 
      "crewGenre":"Girl's hip-hop", 
      "crewName":"Pinky Chicks", 
      "crewLeaderContact":"[email protected]", 
      "crewAsso":"JBlack Studio" 
      } 
     } 
    ] 
} 

我已經做了谷歌多個搜索產生這些嵌套結構,但到Java結果我只得到JSON ..

回答

0

創建POJO類似

public class Crews{ 
    private List<Map<String, String>> crews; 

    // gettes ,setters 

} 

此創建對象類。並設置工作人員並解析此對象