我有两个类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()));
}
}
}
答案 0 :(得分:0)
只需在请求的JSON
中添加一个Body
对象,在Raw Json
中选择Postman
并粘贴以下对象:
注意:在请求的Content-Type
中添加密钥application/json
并将其值设置为Header
{
"title": "Some title",
"artistSeeds": [
"string1",
"string2"
],
"numberOfSongs": 0
}
答案 1 :(得分:0)
将此参数从数据类更改为字符串,
public Response createPlaylist(PlaylistRequest request) {
到
public Response createPlaylist(String request) {
然后使用GSON将其转换为数据类。
PlaylistRequest request = new Gson().fromJson(request, new TypeToken<PlaylistRequest >(){}.getType());