我有两个类PlaylistResource,它具有一个createPlaylist方法,该方法接受一个PlaylistRequest类型的对象。我想在localhost:9999 / playlists上创建一个POST请求,我正在使用Postman,我不确定如何将对请求的PlaylistRequest对象传递给方法createPlaylist。
@XmlType(propOrder= {"title", "artistSeeds", "numberOfSongs"})
@XmlAccessorType(XmlAccessType.FIELD)
public class PlaylistRequest {
private String title = "";
@XmlElement(name = "seeds")
private List<String> artistSeeds;
@XmlElement (name = "size")
private int numberOfSongs = 0;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<String> getArtistSeeds() {
return artistSeeds;
}
public void setArtistSeeds(List<String> artistSeeds) {
this.artistSeeds = artistSeeds;
}
public int getNumberOfSongs() {
return numberOfSongs;
}
public void setNumberOfSongs(int numberOfSongs) {
this.numberOfSongs = numberOfSongs;
}
}
另一类:
@Path("playlists")
public class PlaylistResource implements PlaylistApi {
@Override
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createPlaylist(PlaylistRequest request) {
if(request == null) {
System.out.println("Was here");
throw new ClientRequestException(new ErrorMessage("no parameter passed."));
}
try {
List<Song> playList = new ArrayList<>();
List<Song> songs = new ArrayList<>();
List<String> artistsIds = new ArrayList<>();
ArtistResource artistsResources = new ArtistResource();
int playlistDefaultSize = 10;
int i = 0;
do {
playList.add(songs.get(i));
i++;
}while( i < playlistDefaultSize);
Playlist playlist = new Playlist();
playlist.setTitle(request.getTitle());
playlist.setSize(songs.size());
playlist.setTracks(playList);
return Response.status(Response.Status.CREATED.getStatusCode()).entity(playlist).build();
} catch (Exception e) {
throw new RemoteApiException(new ErrorMessage(e.getMessage()));
}
}
}
最佳答案
将此参数从数据类更改为字符串,public Response createPlaylist(PlaylistRequest request) {
至public Response createPlaylist(String request) {
然后使用GSON将其转换为您的数据类。
PlaylistRequest request = new Gson().fromJson(request, new TypeToken<PlaylistRequest >(){}.getType());