【问题标题】:Spring Boot Json FormatSpring Boot Json 格式
【发布时间】:2023-03-15 20:56:01
【问题描述】:

我想使用 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 应用程序。

【问题讨论】:

    标签: json spring-boot


    【解决方案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

    【讨论】:

      猜你喜欢
      • 2016-09-19
      • 1970-01-01
      • 2015-07-09
      • 2017-10-13
      • 2015-05-20
      • 2015-05-18
      • 2019-01-19
      • 2018-08-14
      相关资源
      最近更新 更多