我想使用SpringBoot创建如下所示的Json格式。
[
{
"name": "foo",
"albums": [
{
"title": "album_one",
"artist": "foo",
"ntracks": 12
},
{
"title": "album_two",
"artist": "foo",
"ntracks": 15
}
]
},
{
"name": "bar",
"albums": [
{
"title": "foo walks into a bar",
"artist": "bar",
"ntracks": 12
},
{
"title": "album_song",
"artist": "bar",
"ntracks": 17
}
]
}]
请帮助我,请参考弹簧启动应用程序,这有助于创建类似的Json格式。
答案 0 :(得分:-1)
你不需要弹簧靴,你可以使用杰克逊。
您只需要定义bean,如:
public class ArtistInfo {
private String name;
private List<Album> albums;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Album> getAlbums() {
return albums;
}
public void setAlbums(List<Album> albums) {
this.albums = albums;
}
public static class Album {
private String title;
private String artist;
private int ntracks;
public Album(String title, String artist, int ntracks) {
super();
this.title = title;
this.artist = artist;
this.ntracks = ntracks;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getArtist() {
return artist;
}
public void setArtist(String artist) {
this.artist = artist;
}
public int getNtracks() {
return ntracks;
}
public void setNtracks(int ntracks) {
this.ntracks = ntracks;
}
}
}
现在您可以使用Jackson对象映射器来生成JSON: 初始化 ArtistInfo
的列表ObjectMapper mapper = new ObjectMapper();
List<ArtistInfo> artistInfos = initData();
String json = mapper.writeValueAsString(artistInfos);
System.out.println(json);
如果将此与Spring REST控制器一起使用,如果返回ArtistInfo列表,则spring将生成json