When
I wrote RESTful client in Java with JAX-RS 2.0 Client API, I thought that JSON
serialization/deserialization was not working with Jersey 2.0-m3.
But, in fact, it works as designed and Martin Matula gives us the solution in his second comment and in JIRA).
But, in fact, it works as designed and Martin Matula gives us the solution in his second comment and in JIRA).
To
use the JSON serialization/deserialization (with Jersey 2.0m3), you have to:
- enable the JsonFeature on the client with the line:
client.configuration().enable(new JsonFeature()); - and add the jars:
jersey-media-json-2.0, jackson-jaxrs, jackson-core-asl, jackson-mapper-asl and jackson-xc
JavaClientRESTFul20Extend.java |
package javaclientrestful20; import java.util.List; import javax.ws.rs.client.Client; import javax.ws.rs.core.GenericType; import javax.ws.rs.core.MediaType; import javax.ws.rs.ext.ClientFactory; import org.glassfish.jersey.media.json.JsonFeature; public class JavaClientRESTFul20Extend { // curl http://localhost:8080/RESTfulServices/rs/ArtisteNameBeginningBy/Arc public static void main(String[] args) { //String artistBeginBy = "Arc"; String artistBeginBy = "Arch"; JavaClientRESTFul20Extend clientfindArtistByName = new JavaClientRESTFul20Extend(); List<Music> listMusic = clientfindArtistByName.findArtistByName(artistBeginBy); System.out.println("listMusic : "+listMusic); } protected List<Music> findArtistByName(String artistBeginBy){ Client client = ClientFactory.newClient(); client.configuration().enable(new JsonFeature()); ListMusic listMusic = client.target("http://localhost:8080/RESTfulServices/rs/ArtisteNameBeginningBy/") .path("{beginBy}") .pathParam("beginBy", artistBeginBy) .request(MediaType.APPLICATION_JSON) .get(ListMusic.class); return listMusic.getMusic(); } }
I use a class (ListMusic.java) to wrap the list, because my
restful service returns something like this:
{"music":[{"albumTitle":"Funeral","artisteName":"Arcade
Fire","id":"10"},{"albumTitle":"Neon
bible","artisteName":"Arcade
Fire","id":"11"}]}
[{"albumTitle":"Funeral","artisteName":"Arcade
Fire","id":"10"},{"albumTitle":"Neon
bible","artisteName":"Arcade
Fire","id":"11"}]
ListMusic.java |
package javaclientrestful20; import java.util.ArrayList; import java.util.List; public class ListMusic { List<Music> music = new ArrayList(); public List<Music> getMusic() { return music; } public void setMusic(List<Music> music) { this.music = music; } public String toString(){ return music.toString(); } }
Aucun commentaire:
Enregistrer un commentaire