我正在寻找一个 simple Json (de)serializer for Java,它可能适用于 GWT。我搜索了一下,发现一些解决方案要么需要注释每个成员,要么定义无用的接口(interface)。挺无聊的。为什么我们没有一些非常简单的东西,比如
class MyBean {
...
}
new GoodSerializer().makeString(new MyBean());
new GoodSerializer().makeObject("{ ... }", MyBean.class)
最佳答案
看看 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;
}-*/;
}
一旦定义了覆盖类型,就很容易从 JSON 创建一个 JavaScript 对象并在 Java 中访问它的属性:
public static final native Customer buildCustomer(String json) /*-{
return eval('(' + json + ')');
}-*/;
如果你想要对象的 JSON 表示,你可以将覆盖类型包装在一个 JSONObject 中:
Customer customer = buildCustomer("{'Bart', 'Simpson'}");
customer.setFirstName("Lisa");
// Displays {"first_name":"Lisa","last_name":"Simpson"}
Window.alert(new JSONObject(customer).toString());
关于与 GWT 一起使用的 Json <-> Java 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/683123/