我是Spring新手,目前我很难通过另一个POJO类访问POJO类的方法。
这是我的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
}
]}]
这是我的课程
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 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;}
}
我想通过ArtistInfo类访问Album Class的getTitle()方法,如:
ArtistInfo artistinfo = new ArtistInfo();
artistinfo.getAlbums().getTitle();
我知道这是错误的,因为artistinfo.getAlbums()返回一个它不返回对象的列表。如果我添加另一个字段(ArtistInfo中的Album类的Object),它会影响Json格式,如果有任何方式来自artistinfo类的acess getTitle()或者ArtistInfo类中的任何修改将有助于它。
请帮我解决这个问题.......... 提前谢谢。
答案 0 :(得分:0)
要获取艺术家的所有标题,您可以使用以下代码
List<String> titles = artistInfo.getAlbums()
.stream()
.map(Album::getTitle)
.collect(Collectors.toList());