Java到JSON(带/嵌套元素)

时间:2014-11-05 14:45:33

标签: java json jackson

我正在尝试从这个java对象创建一个JSON表示。我正在使用杰克逊。

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", "jblack@jblack.com");
    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":"jblack@jblack.com",
            "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":"jblack@jblack.com",
            "crewAsso":"JBlack Studio"
            }
        }
    ]
}

我在Google上进行了多次搜索以生成这些嵌套结构,但我只获得了Java结果的JSON ..

1 个答案:

答案 0 :(得分:0)

创建类似

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

   // gettes ,setters

}

为此类创建对象。并设置工作人员并解析此对象