resteasy其实是个很好用的类库,下面介绍下如何使用Resteay去
在JAXB和JSON中进行转换。注意resteasy使用的是JettisonJSONlibrary
(地址:)
1)pom.xml文件的设置
<repositories>
<repository>
<id>JBossrepository</id>
<url>https://repository.jboss.org/nexus/content/groups/public-jboss/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxrs</artifactId>
<version>2.2.1.GA</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxb-provider</artifactId>
<version>2.2.0.GA</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jettison-provider</artifactId>
<version>2.2.0.GA</version>
</dependency>
</dependencies>
2)写一个类,使用JAXB
Java代码
importjavax.xml.bind.annotation.XmlAttribute;
importjavax.xml.bind.annotation.XmlElement;
importjavax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="movie")
publicclassMovie{
Stringname;
Stringdirector;
intyear;
@XmlElement
publicStringgetName(){
returnname;
}
publicvoidsetName(Stringname){
this.name=name;
}
@XmlElement
publicStringgetDirector(){
returndirector;
}
publicvoidsetDirector(Stringdirector){
this.director=director;
}
@XmlAttribute
publicintgetYear(){
returnyear;
}
publicvoidsetYear(intyear){
this.year=year;
}
}
importjavax.xml.bind.annotation.XmlAttribute;
importjavax.xml.bind.annotation.XmlElement;
importjavax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="movie")
publicclassMovie{
Stringname;
Stringdirector;
intyear;
@XmlElement
publicStringgetName(){
returnname;
}
publicvoidsetName(Stringname){
this.name=name;
}
@XmlElement
publicStringgetDirector(){
returndirector;
}
publicvoidsetDirector(Stringdirector){
this.director=director;
}
@XmlAttribute
publicintgetYear(){
returnyear;
}
publicvoidsetYear(intyear){
this.year=year;
}
}
3)然后我们就可以把上面的pojo类转变为json了,看下jboss的reseteasy是如何做的,
Java代码
importjavax.ws.rs.GET;
importjavax.ws.rs.Path;
importjavax.ws.rs.Produces;
importorg.jboss.resteasy.annotations.providers.jaxb.json.BadgerFish;
@Path("/json/movie")
publicclassJSONService{
@BadgerFish
@GET
@Path("/get")
@Produces("application/json")
publicMoviegetMovieInJSON(){
Moviemovie=newMovie();
movie.setName("Transformers:DarkoftheMoon")