RESTEasy 使用 Jettison JSON 库来实现 JAXB 和 JSON对象的相互转换.
1. pom.xml
JBoss repository https://repository.jboss.org/nexus/content/groups/public-jboss/ org.jboss.resteasy resteasy-jaxrs 2.2.1.GA org.jboss.resteasy resteasy-jaxb-provider 2.2.0.GA org.jboss.resteasy resteasy-jettison-provider 2.2.0.GA
2.JAXB XML Provider
创建一个对象, 使用 JAXB 注解. 首先使用 XML 提供? 然后我们使用 @BadgerFish 注解转换成 JSON 格式.
package com.mkyong.rest; 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. JAX-RS
要想返回JSON文件格式,使用 @BadgerFish 和 @Produces(“application/json”) 注解即可.
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. Demo
访问地址 “/json/movie/get”,将返回
{ "movie": { "@year":"2011", "director":{ "$":"Michael Bay" }, "name":{ "$":"Transformers: Dark of the Moon" } } }