如何使用Java通过Web服务以JSON格式公开数据?

有没有一种简单的方法可以使用java将数据返回到JSON中的Web服务客户端? 我很喜欢servlets,spring等。

对我来说, 最好的Java < - > JSON解析器是XStream (是的,我真的在谈论json,而不是关于xml)。 XStream已经处理了循环依赖,并且有一个简单而强大的api,你可以编写你的驱动程序,转换器等等。

亲切的问候

值得一看泽西岛 。 Jersey可以轻松地将restful Web服务公开为xml和/或JSON。

一个例子……从一个简单的类开始

@XmlType(name = "", propOrder = { "id", "text" }) @XmlRootElement(name = "blah") public class Blah implements Serializable { private Integer id; private String text; public Blah(Integer id, String text) { this.id = id; this.text = text; } @XmlElement public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @XmlElement public String getText() { return text; } public void setText(String value) { this.text = value; } } 

然后创建一个资源

 @Path("/blah") public class BlahResource { private Set blahs = new HashSet(); @Context private UriInfo context; public BlahResource() { blahs.add(new Blah(1, "blah the first")); blahs.add(new Blah(2, "blah the second")); } @GET @Path("/{id}") @ProduceMime({"application/json", "application/xml"}) public Blah getBlah(@PathParam("id") Integer id) { for (Blah blah : blahs) { if (blah.getId().equals(id)) { return blah; } } throw new NotFoundException("not found"); } } 

并暴露它。 有很多方法可以做到这一点,例如使用Jersey的ServletContainer。 (web.xml)中

  jersey com.sun.jersey.spi.container.servlet.ServletContainer 1   jersey /*  

这就是你需要做的…弹出你的浏览器并浏览到http:// localhost / blah / 1 。 默认情况下,您将看到XML输出。 如果您使用的是FireFox,请安装TamperData并将您的accept标头更改为application/json以查看JSON输出。

显然还有很多东西,但泽西岛让所有这些东西都很容易。

祝你好运!

我们一直在使用Flexjson将Java对象转换为JSON,并且发现它非常易于使用。 http://flexjson.sourceforge.net

这里有些例子:

 public String searchCars() { List cars = carsService.getCars(manufacturerId); return new JSONSerializer().serialize(cars); } 

它有一些很酷的function,例如deepSerialize来发送整个图形,它不会破坏双向关系。

 new JSONSerializer().deepSerialize(user); 

在服务器端格式化日期通常也很方便

 new JSONSerializer().transform( new DateTransformer("dd/MM/yyyy"),"startDate","endDate" ).serialize(contract); 

对! 看看json-lib

这是我自己的代码中的一个简化代码片段,它发送了一组我的域对象:

 private String getJsonDocumenent(Object myObj) ( String result = "oops"; try { JSONArray jsonArray = JSONArray.fromObject(myObj); result = jsonArray.toString(2); //indent = 2 } catch (net.sf.json.JSONException je) { throw je; } return result; } 

我发现google-gson引人注目。 它转换为JSON并返回。 http://code.google.com/p/google-gson/它非常灵活,可以直接处理对象的复杂性。 我喜欢它对generics的支持。

 /* * we're looking for results in the form * {"id":123,"name":thename},{"id":456,"name":theOtherName},... * * TypeToken is Gson--allows us to tell Gson the data we're dealing with * for easier serialization. */ Type mapType = new TypeToken>>(){}.getType(); List> resultList = new LinkedList>(); for (Map.Entry pair : sortedMap.entrySet()) { Map idNameMap = new HashMap(); idNameMap.put("id", pair.getKey()); idNameMap.put("name", pair.getValue()); resultList.add(idNameMap); } return (new Gson()).toJson(resultList, mapType); 

对于Java中的RESTful Web服务,还要查看Restlet API ,它为REST Web服务(服务器和客户端,容器或独立服务器)提供了非常强大和灵活的抽象,并且还与Spring和JSON很好地集成。

如前所述, Jersey (JAX-RS impl)是使用的框架; 但是对于Java对象与JSON的基本映射, Tutorial很好。 与许多替代方案不同,它不使用奇怪的XML兼容性约定,而是读取和写入直接映射到对象和从对象映射的干净JSON。 它也没有null的问题(缺少条目和一个具有null之间存在差异),空列表或字符串(两者都与空值不同)。

Jackson也可以使用JAX-RS提供者jar,甚至只需手动操作。 同样,它很容易与普通的旧servlet一起使用; 只需获取输入/输出流,调用ObjectMapper.readValue()和.writeValue(),就是这样。

我一直在使用jaxws-json来提供JSON格式的Web服务。 你可以查看项目https://jax-ws-commons.dev.java.net/json/ 。

这是一个很好的项目,一旦你了解它,你会发现它是多么迷人。