Json <-> 适用于 GWT 的 Java 序列化
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/683123/
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
Json <-> Java serialization that works with GWT
提问by amartynov
I am looking for a simpleJson (de)serializer for Java that might work with GWT. I have googled a bit and found some solutions that either require annotate every member or define useless interfaces. Quite a boring. Why don't we have something really simple like
我正在寻找一个简单的Json(反)序列化器,它可以与 GWT 一起使用。我用谷歌搜索了一下,发现了一些需要注释每个成员或定义无用接口的解决方案。挺无聊的。为什么我们没有真正简单的东西
class MyBean {
...
}
new GoodSerializer().makeString(new MyBean());
new GoodSerializer().makeObject("{ ... }", MyBean.class)
采纳答案by Chris Kentfield
Take a look at GWT's Overlay Types. I think this is by far the easiest way to work with JSON in GWT. Here's a modified code example from the linked article:
看看 GWT 的Overlay Types。我认为这是迄今为止在 GWT 中使用 JSON 的最简单方法。这是链接文章中修改后的代码示例:
public class Customer extends JavaScriptObject {
public final native String getFirstName() /*-{
return this.first_name;
}-*/;
public final native void setFirstName(String value) /*-{
this.first_name = value;
}-*/;
public final native String getLastName() /*-{
return this.last_name;
}-*/;
public final native void setLastName(String value) /*-{
this.last_name = value;
}-*/;
}
Once you have the overlay type defined, it's easy to create a JavaScript object from JSON and access its properties in Java:
一旦定义了覆盖类型,就很容易从 JSON 创建一个 JavaScript 对象并在 Java 中访问它的属性:
public static final native Customer buildCustomer(String json) /*-{
return eval('(' + json + ')');
}-*/;
If you want the JSON representation of the object again, you can wrap the overlay type in a JSONObject:
如果您再次想要对象的 JSON 表示,您可以将覆盖类型包装在 JSONObject 中:
Customer customer = buildCustomer("{'Bart', 'Simpson'}");
customer.setFirstName("Lisa");
// Displays {"first_name":"Lisa","last_name":"Simpson"}
Window.alert(new JSONObject(customer).toString());
回答by rjrjr
Another thing to try is the new AutoBeanframework introduced with GWT 2.1.
另一件要尝试的事情是GWT 2.1 中引入的新AutoBean框架。
You define interfaces for your beans and a factory that vends them, and GWT generates implementations for you.
您为 bean 定义接口和出售它们的工厂,GWT 为您生成实现。
interface MyBean {
String getFoo();
void setFoo(String foo);
}
interface MyBiggerBean {
List<MyBean> getBeans();
void setBeans(List<MyBean> beans>;
}
interface Beanery extends AutoBeanFactory{
AutoBean<MyBean> makeBean();
AutoBean<MyBiggerBean> makeBigBean();
}
Beanery beanFactory = GWT.create(Beanery.class);
void go() {
MyBean bean = beanFactory.makeBean().as();
bean.setFoo("Hello, beans");
}
The AutoBeanCodexcan be used to serialize them to and from json.
该AutoBeanCodex可用于它们序列,并从JSON。
AutoBean<MyBean> autoBean = AutoBeanUtils.getAutoBean(bean);
String asJson = AutoBeanCodex.encode(autoBean).getPayload();
AutoBean<MyBean> autoBeanCloneAB =
AutoBeanCodex.decode(beanFactory, MyBean.class, asJson );
MyBean autoBeanClone = autoBeanCloneAB.as();
assertTrue(AutoBeanUtils.deepEquals(autoBean, autoBeanClone));
They work on the server side too — use AutoBeanFactoryMagic.create(Beanery.class)instead of GWT.create(Beanery.class).
它们也适用于服务器端 - 使用AutoBeanFactoryMagic.create(Beanery.class)而不是GWT.create(Beanery.class).
回答by Eric Nguyen
The simplest way would be to use GWT's built-in JSON API. Here's the documentation. And here is a great tutorialon how to use it.
最简单的方法是使用 GWT 的内置 JSON API。这是文档。这是一个关于如何使用它的很棒的教程。
It's as simple as this:
就这么简单:
String json = //json string
JSONValue value = JSONParser.parse(json);
The JSONValue API is pretty cool. It lets you chain validations as you extract values from the JSON object so that exceptions will be thrown if anything's amiss with the format.
JSONValue API 非常酷。它允许您在从 JSON 对象中提取值时链接验证,以便在格式有任何问题时抛出异常。
回答by amartynov
It seems that I found the right answer to my question
似乎我找到了我问题的正确答案
I figured out that bean to json and json to bean conversion in GWT isn't a trivial task. Known libraries would not work because GWT would require their full source code and this source code must use only Java classes that are amoung emulated by GWT. Also, you cannot use reflection in GWT. Very tough requirements!
我发现 GWT 中 bean 到 json 和 json 到 bean 的转换并不是一项简单的任务。已知的库将无法工作,因为 GWT 需要它们的完整源代码,而此源代码必须仅使用 GWT 模拟的 Java 类。此外,您不能在 GWT 中使用反射。非常苛刻的要求!
I found the only existing solution named gwt-jsonizer. It uses a custom Generatorclass and requires a satellite interface for each "jsonable" bean. Unfortunately, it does not work without patching on the latest version of GWT and has not been updated for a long time.
我找到了唯一现有的名为gwt-jsonizer 的解决方案。它使用一个自定义的Generator类,并且每个“jsonable”bean 都需要一个卫星接口。不幸的是,如果没有在最新版本的 GWT 上打补丁,它就无法运行,并且已经很长时间没有更新了。
So, I personally decided that it is cheaper and faster to make my beans khow how to convert themselves to and from json. Like this:
所以,我个人认为让我的 bean 知道如何将自己转换为 json 和从 json 转换更便宜、更快捷。像这样:
public class SmartBean {
private String name;
public String getName() { return name; }
public void setName(String value) { name = value; }
public JSONObject toJson() {
JSONObject result = new JSONObject();
result.put("name", new JSONString(this.name));
return result;
}
public void fromJson(JSONObject value) {
this.name = value.get("name").isString().stringValue();
}
}
JSONxxxxare GWT built-in classes that provide low-level json support.
JSONxxxx是提供低级 json 支持的 GWT 内置类。
回答by Saeed Zarinfam
RestyGWTis a powerful library for encoding or decoding Java Object to JSON in GWT:
RestyGWT是一个强大的库,用于在 GWT 中将 Java 对象编码或解码为 JSON:
import javax.ws.rs.POST;
...
public interface PizzaOrderCodec extends JsonEncoderDecoder<PizzaOrder> {
}
Then:
然后:
// GWT will implement the interface for you
PizzaOrderCodec codec = GWT.create(PizzaOrderCodec.class);
// Encoding an object to json
PizzaOrder order = ...
JSONValue json = codec.encode(order);
// decoding an object to from json
PizzaOrder other = codec.decode(json);
It has also got several easy to use API for consuming Restful web services.
它还提供了几个易于使用的 API 来使用 Restful Web 服务。
Have a nice time.
过得愉快。
回答by Krunoslav Funtak
Check this:
检查这个:
GWT Professional JSON Serializer: http://code.google.com/p/gwtprojsonserializer/
GWT 专业 JSON 序列化程序:http: //code.google.com/p/gwtprojsonserializer/
!Works with GWT 2.0+!
!适用于 GWT 2.0+!
回答by Phaedrus
json.org/java seems to be included with GWT these days:
json.org/java 现在似乎包含在 GWT 中:
gwt-servlet-deps.jar\org\json\
gwt-servlet-deps.jar\org\json\
Or, this project seems to be comprehensive: http://code.google.com/p/piriti/
或者,这个项目似乎很全面:http: //code.google.com/p/piriti/
回答by mooreds
In Google Web Toolkit Applications, pages 510 to 522, the author, Ryan Dewsbury, shows how to use GWT code generation to do serialization to and from XML and JSON documents.
在 Google Web Toolkit Applications 的第 510 到 522 页中,作者 Ryan Dewsbury 展示了如何使用 GWT 代码生成在 XML 和 JSON 文档之间进行序列化。
You can download the code here; you want the chapter 10 code bundles, and then you want to look in the src/com/gwtapps/serialization package. I did not see a license for this code, but have emailed the author to see what he says. I'll update this if he replies.
你可以在这里下载代码;您需要第 10 章的代码包,然后您需要查看 src/com/gwtapps/serialization 包。我没有看到此代码的许可证,但已通过电子邮件向作者发送电子邮件以查看他的内容。如果他回复,我会更新这个。
Issues with this solution:
此解决方案的问题:
- You have to add a marker interface on all your objects that you want serialized (he uses java.io.Serializable but I imagine you could use others--if you are using hibernate for your backend, your pojos might already be tagged like this).
- The code only supports string properties; it could be extended.
- The code is only written for 1.4 and 1.5.
- 你必须在你想要序列化的所有对象上添加一个标记接口(他使用 java.io.Serializable 但我想你可以使用其他的——如果你在后端使用 hibernate,你的 pojos 可能已经被标记为这样) .
- 代码只支持字符串属性;它可以延长。
- 代码仅针对 1.4 和 1.5 编写。
So, this is not an out of the box solution, but a great starting point for someone to build a JSON serializer that fits with GWT. Combine that with a JSON serializer on the server side, like json-liband you're good to go.
因此,这不是一个开箱即用的解决方案,而是构建适合 GWT 的 JSON 序列化程序的一个很好的起点。将它与服务器端的 JSON 序列化程序(如json-lib)结合起来,您就可以开始使用了。
I also found this project(again, some marker interface is required).
我也找到了这个项目(同样,需要一些标记界面)。
回答by John
Try this serializer from Google Code: http://code.google.com/p/json-io/
从谷歌代码试试这个序列化程序:http: //code.google.com/p/json-io/
If you need to write or read JSON format in Java, this is the tool to use. No need to create extra classes, etc. Convert a Java object graph to JSON format in one call. Do the opposite - create a JSON String or Stream to Java objects. This is the fastest library I have seen yet to do this. It is faster than ObjectOutputStream and ObjectInputStream in most cases, which use binary format.
如果您需要用 Java 编写或读取 JSON 格式,这是要使用的工具。无需创建额外的类等。只需一次调用即可将 Java 对象图转换为 JSON 格式。做相反的事情 - 创建一个 JSON String 或 Stream to Java 对象。这是我见过的最快的图书馆。在大多数情况下,它比使用二进制格式的 ObjectOutputStream 和 ObjectInputStream 更快。
Very handy utility.
非常方便的实用程序。
回答by Bruno Bossola
You may want to checkout this project https://gerrit.googlesource.com/gwtjsonrpc/
您可能想查看此项目https://gerrit.googlesource.com/gwtjsonrpc/
It's a library created in order to support a code review system for Android, Gerrit, but it's a stand-alone module meant to be embedded into any GWT project, not just Gerrit.
它是一个为支持 Android Gerrit 代码系统而创建的库,但它是一个独立的模块,旨在嵌入到任何 GWT 项目中,而不仅仅是 Gerrit。
A reasonable tutorial is probably the READMEin the top level of the directory. It's quite similar to standard GWT RPC but it uses JSON encoding. It also has built-in XSRF protection.
一个合理的教程可能是目录顶层的README。它与标准 GWT RPC 非常相似,但它使用 JSON 编码。它还具有内置的 XSRF 保护。

