如何使用 Java 通过 Web 服务以 JSON 格式公开数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/57689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I expose data in a JSON format through a web service using Java?
提问by Adrian Anttila
Is there an easy way to return data to web service clients in JSON using java? I'm fine with servlets, spring, etc.
有没有一种简单的方法可以使用 java 以 JSON 格式将数据返回给 Web 服务客户端?我对 servlet、spring 等没问题。
采纳答案by marcospereira
To me, the best Java <-> JSON parser is XStream(yes, I'm really talking about json, not about xml). XStream already deals with circular dependencies and has a simple and powerful api where you could write yours drivers, converters and so on.
对我来说,最好的 Java <-> JSON 解析器是 XStream(是的,我真的在谈论 json,而不是 xml)。XStream 已经处理了循环依赖,并有一个简单而强大的 api,你可以在其中编写驱动程序、转换器等。
Kind Regards
亲切的问候
回答by Adrian Anttila
http://www.json.org/java/index.htmlhas what you need.
回答by Stu Thompson
Yup! Check out json-lib
是的!查看json-lib
Here is a simplified code snippet from my own codethat send a set of my domain objects:
这是我自己的代码中的一个简化代码片段,用于发送一组我的域对象:
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;
}
回答by Geekygecko
We have been using Flexjson for converting Java objects to JSON and have found it very easy to use. http://flexjson.sourceforge.net
我们一直在使用 Flexjson 将 Java 对象转换为 JSON,并且发现它非常易于使用。 http://flexjson.sourceforge.net
Here are some examples:
这里有些例子:
public String searchCars() {
List<Car> cars = carsService.getCars(manufacturerId);
return new JSONSerializer().serialize(cars);
}
It has some cool features such as deepSerialize to send the entire graph and it doesn't break with bi directional relationships.
它有一些很酷的功能,例如 deepSerialize 可以发送整个图形,并且不会破坏双向关系。
new JSONSerializer().deepSerialize(user);
Formatting dates on the server side is often handy too
在服务器端格式化日期通常也很方便
new JSONSerializer().transform(
new DateTransformer("dd/MM/yyyy"),"startDate","endDate"
).serialize(contract);
回答by Henning
For RESTful web services in Java, also check out the Restlet APIwhich provides a very powerful and flexible abstraction for REST web services (both server and client, in a container or standalone), and also integrates nicely with Spring and JSON.
对于 Java 中的 RESTful Web 服务,还可以查看Restlet API,它为 REST Web 服务(服务器和客户端,容器或独立)提供了非常强大和灵活的抽象,并且还与 Spring 和 JSON 很好地集成。
回答by blahspam
It might be worth looking into Jersey. Jersey makes it easy to expose restful web services as xml and/or JSON.
可能值得研究Jersey。Jersey 可以轻松地将 Restful Web 服务公开为 xml 和/或 JSON。
An example... start with a simple class
一个例子...从一个简单的类开始
@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; }
}
Then create a Resource
然后创建一个资源
@Path("/blah")
public class BlahResource {
private Set<Blah> blahs = new HashSet<Blah>();
@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");
}
}
and expose it. There are many ways to do this, such as by using Jersey's ServletContainer. (web.xml)
并揭露它。有很多方法可以做到这一点,例如使用 Jersey 的 ServletContainer。(web.xml)
<servlet>
<servlet-name>jersey</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
Thats all you need to do... pop open your browser and browse to http://localhost/blah/1. By default you will see XML output. If you are using FireFox, install TamperData and change your accept
header to application/json
to see the JSON output.
这就是你需要做的所有事情......打开你的浏览器并浏览到http://localhost/blah/1。默认情况下,您将看到 XML 输出。如果您使用的是 FireFox,请安装 TamperData 并将您的accept
标头更改为application/json
以查看 JSON 输出。
Obviously there is much more to it, but Jerseymakes all that stuff quite easy.
显然还有更多内容,但泽西岛让所有这些事情变得非常简单。
Good luck!
祝你好运!
回答by StaxMan
As already mentioned, Jersey(JAX-RS impl) is the framework to use; but for basic mapping of Java objects to/from JSON, Tutorialis good. Unlike many alternatives, it does not use strange XML-compatibility conventions but reads and writes clean JSON that directly maps to and from objects. It also has no problems with null (there is difference between missing entry and one having null), empty Lists or Strings (both are distinct from nulls).
如前所述,Jersey(JAX-RS impl) 是要使用的框架;但是对于Java对象到/从JSON的基本映射,教程很好。与许多替代方案不同,它不使用奇怪的 XML 兼容性约定,而是读取和写入直接映射到对象和从对象映射的干净 JSON。它也没有空值(缺少条目和具有空值的条目之间存在差异)、空列表或字符串(两者都与空值不同)的问题。
Hymanson works nicely with Jersey as well, either using JAX-RS provider jar, or even just manually. Similarly it's trivially easy to use with plain old servlets; just get input/output stream, call ObjectMapper.readValue() and .writeValue(), and that's about it.
Hymanson 也可以很好地与 Jersey 一起使用,无论是使用 JAX-RS 提供程序 jar,还是手动操作。同样,使用普通的旧 servlet 也很容易;只需获取输入/输出流,调用 ObjectMapper.readValue() 和 .writeValue(),就可以了。
回答by jon
I have found google-gson compelling. It converts to JSON and back. http://code.google.com/p/google-gson/It's very flexible and can handle complexities with objects in a straightforward manner. I love its support for generics.
我发现 google-gson 很有说服力。它转换为 JSON 并返回。http://code.google.com/p/google-gson/它非常灵活,可以直接处理对象的复杂性。我喜欢它对泛型的支持。
/*
* 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<List<Map<String, String>>>(){}.getType();
List<Map<String, String>> resultList = new LinkedList<Map<String, String>>();
for (Map.Entry<String, String> pair : sortedMap.entrySet()) {
Map<String, String> idNameMap = new HashMap<String, String>();
idNameMap.put("id", pair.getKey());
idNameMap.put("name", pair.getValue());
resultList.add(idNameMap);
}
return (new Gson()).toJson(resultList, mapType);
回答by lwpro2
I have been using jaxws-json, for providing JSON format web services. you can check the project https://jax-ws-commons.dev.java.net/json/.
我一直在使用 jaxws-json,用于提供 JSON 格式的 Web 服务。您可以查看项目https://jax-ws-commons.dev.java.net/json/。
it's a nice project, once you get it up, you'll find out how charming it is.
这是一个不错的项目,一旦你搞定了,你就会发现它有多么迷人。