javascript - GWT JsType 数组转换

标签 javascript gwt gwt-jsinterop

当我有 JSON 对象时,例如:

{
    "asset": {
        "properties": [{
            "name": "xxx",
            "id": "yy"
        }]
    }
}

然后我有像这样的 JsInterop 包装器:

@JsType
public class Asset {

   @JsProperty
   public native jsinterop.base.JsArrayLike<Property> getProperties();

}

和:

@JsType
public class Property {

   @JsProperty
   public native String getName();
   @JsProperty
   public native String getId();
}

当我在代码中的某个位置尝试访问数据时,当我尝试访问 Property 对象的属性时,它会失败。

例如:

Asset asset = dataProvider.getAssets();
console.log(assets) //works ok: => {"properties":Array(1)}
console.log(asset.getProperties()) //works ok:  => Array(1)
console.log(asset.getProperties().getAt(0)) //works ok:  => {"name":"xxx","id":"yy"}
console.log(asset.getProperties().getAt(0).getName() //does not work:  => Uncaught exception: undefined

或者如果我创建 Assets 和属性类 (isNative=true):

Uncaught exception: Cannot read property "company" of undefined.

我检查过,如果我在尝试获取名称或 ID 时编译应用程序,代码将编译为:

castTo(asset.properties[0], 125)

或者如果(isNative=true):

castToNative(asset.properties[0], $wnd.com.company.project.Property)

首先我认为这是因为我实现了数组的包装器,但是我发现了“jsinterop.base.JsArrayLike”,所以我认为这会解决我的问题,但错误仍然相同。我错过了什么吗?我真的很想使用 JsInterop 而不是 JSNI 方法和 Overlay 类型,但我无法绕过这些数组。

最佳答案

当您处理 JSON 数据时,您会得到普通的旧 ObjectArray 对象。所以你需要使用

@JsType(isNative=true, namespace=JsPackage.GLOBAL, name="Object")

您可以改用接口(interface),它不会进行强制转换和类型检查。

关于javascript - GWT JsType 数组转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49116169/

相关文章:

Javascript: "+"符号连接而不是给出变量总和

javascript - 不确定技术术语 - HTML/CSS/Javascript 表格问题

gwt - 在端口 80 上链接 apache web 服务器,在端口 8080 上链接 tomcat webapp

java - 最小化 GWT 应用程序的编译大小

javascript - 无法通过 GWT 中的 JsInterop 将 Java 类导出到 JavaScript

java - 如何将对象转换为 JsType?

javascript - 使用 float :left vs display:inline-block 的 jQuery UI 拖放排序比较

javascript - 使用 rangy-position.js 获取所选文本的 x-y 位置

java - 将日期和时区从 GAE 服务器发送到 GWT 客户端

gwt - 检查 GWT Elemental2 覆盖中方法或属性的可用性