json - Spring Boot Json 格式
问题描述
我想使用 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 格式的 Spring Boot 应用程序。
解决方案
你不需要弹簧靴,你可以用杰克逊来做。
您只需要像这样定义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: Initialize List of ArtistInfo
ObjectMapper mapper = new ObjectMapper();
List<ArtistInfo> artistInfos = initData();
String json = mapper.writeValueAsString(artistInfos);
System.out.println(json);
如果您将它与 Spring REST 控制器一起使用,如果您返回 ArtistInfo 列表,spring 将生成 json
推荐阅读
- html - 未找到用于解析的 HTML 响应中的表
- java - 使用 heroku war:deploy myapp.war 时如何在 Heroku 中编辑 Procfile
- javascript - 使用jQuery从jsp到servlet的级联参数
- java - 从 kafka 中检索指定主题中每个分区的最后偏移量
- python - 打印值时如何删除标题和索引
- c# - 如何防止构造函数在值更改时被调用
- javascript - 如何使用 JavaScript 在画布中单击一个圆圈
- wso2 - Ballerina 的整数模除法和整数除法余数
- android - Kotlin 合约在 Android 开发中的用例是什么
- mysql - 如何根据SQL中的第一条记录进行匹配和填充?