resteasy其实是个很好用的类库,下面介绍下如何使用Resteay去
在JAXB和JSON中进行转换。注意resteasy使用的是Jettison JSON library
(地址:http://jettison.codehaus.org/)
1) pom.xml文件的设置
<repositories>
<repository>
<id>JBoss repository</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
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "movie")
public class Movie {
String name;
String director;
int year;
@XmlElement
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@XmlElement
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
@XmlAttribute
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
}
3) 然后我们就可以把上面的pojo类转变为json了,看下jboss的reseteasy是如何做的,
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import org.jboss.resteasy.annotations.providers.jaxb.json.BadgerFish;
@Path("/json/movie")
public class JSONService {
@BadgerFish
@GET
@Path("/get")
@Produces("application/json")
public Movie getMovieInJSON() {
Movie movie = new Movie();
movie.setName("Transformers: Dark of the Moon");
movie.setDirector("Michael Bay");
movie.setYear(2011);
return movie;
}
}
4 当访问“/json/movie/gets"时,就显示对应的json了
{
"movie":
{
"@year":"2011",
"director":{
"$":"Michael Bay"
},
"name":{
"$":"Transformers: Dark of the Moon"
}
}
}
至于这个@BadgerFish有点怪怪的,有待进一步学习