在java中将父节点添加到Json输出

时间:2016-06-02 12:26:49

标签: java json jackson

我已经使用Java中的Jackson将一些信息转换为Json格式。以下是我得到的输出

[{"lat":45.9,"lon":10.9,"title":"Title A1","html":"<h3>Content A1</h3>","icon":"http://maps.google.com/mapfiles/markerA.png"},{"lat":44.8,"lon":1.7,"title":"Title B1","html":"<h3>Content B1</h3>","icon":"http://maps.google.com/mapfiles/markerB.png","show_infowindow":false},{"lat":51.5,"lon":-1.1,"title":"Title C1","html":"<h3>Content C1</h3><p>Lorem Ipsum..</p>","zoom":8,"icon":"http://maps.google.com/mapfiles/markerC.png"}]

我的问题是如何以下面的格式获得它,基本上将Json添加到一个名为locations的根节点

{"locations":[{"lat":45.9,"lon":10.9,"title":"Title A1","html":"<h3>Content A1</h3>","icon":"http://maps.google.com/mapfiles/markerA.png"},{"lat":44.8,"lon":1.7,"title":"Title B1","html":"<h3>Content B1</h3>","icon":"http://maps.google.com/mapfiles/markerB.png","show_infowindow":false},{"lat":51.5,"lon":-1.1,"title":"Title C1","html":"<h3>Content C1</h3><p>Lorem Ipsum..</p>","zoom":8,"icon":"http://maps.google.com/mapfiles/markerC.png"}]}

2 个答案:

答案 0 :(得分:4)

您可以将数组包装成像这样的JSONObject

ObjectMapper mapper = new ObjectMapper();

Map<String, Object> map = new HashMap<String, Object>();

String json = jsonArray.toString();
map.put("locations", json);

json = mapper.writeValueAsString(map);

答案 1 :(得分:0)

您可以通过以下更改来实现此目的。

让我们假设,您的JSON同样基于Bean.java类创建,

[{"lat":45.9,"lon":10.9,"title":"Title A1","html":"<h3>Content A1</h3>","icon":"http://maps.google.com/mapfiles/markerA.png"},{"lat":44.8,"lon":1.7,"title":"Title B1","html":"<h3>Content B1</h3>","icon":"http://maps.google.com/mapfiles/markerB.png","show_infowindow":false},{"lat":51.5,"lon":-1.1,"title":"Title C1","html":"<h3>Content C1</h3><p>Lorem Ipsum..</p>","zoom":8,"icon":"http://maps.google.com/mapfiles/markerC.png"}]

现在,根据您的新要求,您也想要一些东西,

{"locations":[{"lat":45.9,"lon":10.9,"title":"Title A1","html":"<h3>Content A1</h3>","icon":"http://maps.google.com/mapfiles/markerA.png"},{"lat":44.8,"lon":1.7,"title":"Title B1","html":"<h3>Content B1</h3>","icon":"http://maps.google.com/mapfiles/markerB.png","show_infowindow":false},{"lat":51.5,"lon":-1.1,"title":"Title C1","html":"<h3>Content C1</h3><p>Lorem Ipsum..</p>","zoom":8,"icon":"http://maps.google.com/mapfiles/markerC.png"}]}

所以,在这种情况下,你需要创建一个更多的类,让我们说它是SuperBean.java然后它应该是同样的,

public class SuperBean {
     private Bean [] locations;

    public Bean[] getBean() {
        return locations;
    }

    public void setBean(Bean[] locations) {
        this.locations = locations;
    }
}

因此,您的JSON也将同样创建,

{"locations":[......]} // as per your requirement.