使用 RESTEasy + JAXB + Jettison 提供JSON服务

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"
		}
	}
}

关于Zeno Chen

本人涉及的领域较多,杂而不精 程序设计语言: Perl, Java, PHP, Python; 数据库系统: MySQL,Oracle; 偶尔做做电路板的开发,主攻STM32单片机
此条目发表在Java分类目录。将固定链接加入收藏夹。