杰森<->适用于 GWT 的 Java 序列化 [英] Json <-> Java serialization that works with GWT
问题描述
我正在寻找一个简单适用于 Java 的 Json(反)序列化程序,它可以与 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;
}-*/;
}
一旦定义了覆盖类型,就可以轻松地从 JSON 创建 JavaScript 对象并在 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());
这篇关于杰森<->适用于 GWT 的 Java 序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!