Json< - >与GWT协同工作的Java序列化 [英] Json <-> Java serialization that works with GWT
问题描述
我正在寻找一种适用于Java的简单 Json(de)序列化程序,可以与GWT一起使用。我搜索了一下,发现了一些需要注释每个成员或者定义无用接口的解决方案。非常无聊。为什么我们没有像
I am looking for a simple Json (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
class MyBean {
...
}
new GoodSerializer().makeString(new MyBean());
new GoodSerializer().makeObject("{ ... }", MyBean.class)
推荐答案
查看GWT的覆盖类型。我认为这是迄今为止在GWT中使用JSON最简单的方法。这里有一个来自链接文章的修改代码示例:
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:
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;
}-*/;
}
一旦您定义了覆盖类型,就很容易创建一个JavaScript对象JSON并在Java中访问它的属性:
Once you have the overlay type defined, it's easy to create a JavaScript object from JSON and access its properties in Java:
public static final native Customer buildCustomer(String json) /*-{
return eval('(' + json + ')');
}-*/;
如果您想再次使用对象的JSON表示,则可以将叠加类型包装在JSONObject中:
If you want the JSON representation of the object again, you can wrap the overlay type in a JSONObject:
Customer customer = buildCustomer("{'Bart', 'Simpson'}");
customer.setFirstName("Lisa");
// Displays {"first_name":"Lisa","last_name":"Simpson"}
Window.alert(new JSONObject(customer).toString());
这篇关于Json< - >与GWT协同工作的Java序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!