使用 GWT 叠加类型将 JSON 字符串转换为 POJO

Using GWT Overlay type to convert JSON String to POJO

本文关键字:字符串 转换 POJO JSON GWT 叠加 类型 使用      更新时间:2023-09-26

这是我需要转换为POJO以便在我的GWT应用程序中轻松访问的字符串:

{"title":"test","content":"test","id":1,"user":null,"hash":null,"created":1379569937945,"modified":1379569937945,"password":null,"views":0}

看看这个答案:使用 gwt 2.0 解析 json

使用覆盖类型似乎很容易做到。但是,那里的示例显示例如获取 ID:

    public final native int getId() /*-{
        return parseInt(this.u[0]);
    }-*/;

问题是我的 GWT 应用程序可能获取字段顺序的 JSON 字符串可能会更改。为此,我们能做些什么呢?我不是 Javascript 专家,但这段代码显示了获取它在解析的第一个字段上获得的 ID:return parseInt(this.u[0]);我是否正确理解了这一点?就像我的情况一样,如果 ID 字段在 JSON 字符串中的位置会发生变化。

你的 JSON 是:

{
  "title": "test",
  "content": "test",
  "id": 1,
  "user": null,
  "hash": null,
  "created": 1379569937945,
  "modified": 1379569937945,
  "password": null,
  "views": 0
}

只需使用 JavaScript 对象和 JSNI 语法为其创建一个覆盖层(即,一个零开销的 Java 对象,它完全表示和映射您的 JSON 结构),并使用 JsonUtils.safeEval() 安全地评估有效负载并返回覆盖实例。

import com.google.gwt.core.client.JsonUtils;
public class YourFancyName extends JavaScriptObject {
  /**
   * Overlay types always have protected, zero-arg ctors.
   */
  protected YourFancyName() { }
  /**
   * Safely evaluate the JSON payload and create the object instance.
   */
  public static YourFancyName create(String json) {
    return (YourFancyName) JsonUtils.safeEval(json);
  }
  /**
   * Returns the title property.
   */
  public native String getTitle() /*-{
    return this.title;
  }-*/;
  /**
   * Returns the id property.
   */
  public native int getId() /*-{
    return this.id;
  }-*/;
  // And the like...
}

如果您只是尝试使用 GWT 覆盖类型从对象中获取 int,请尝试以下操作:

public final native String getId() /*-{
    return this.id;
}-*/;

或者,如果要获取数组,请执行以下操作:

public final native JsArray getData() /*-{
    return this.data.children;
}-*/;

其中children是名为 data 的元素中的数组。

你有很多选择。

如果你想在js中解析JSON,请查看这篇文章。 如果您的客户端支持它,请使用JSON.parse()或javascript json lib。然后myJsonObject.title将返回"test",而不取决于它在 json 中的位置。

你也可以使用 eval(),这是一个原生的 Js 函数,但如果你不确定 JSON 的来源,可能会执行恶意代码。

但我宁愿使用像JSONParser这样的GWT兼容实用程序。这篇文章有一些有用的信息。出于同样的原因,使用 parseStrict() 时要小心(解析器内部机制也使用 eval())。