首页 > 解决方案 > 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 应用程序。

标签: jsonspring-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


推荐阅读