当我有 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 数据时,您会得到普通的旧 Object
和 Array
对象。所以你需要使用
@JsType(isNative=true, namespace=JsPackage.GLOBAL, name="Object")
或您可以改用接口(interface),它不会进行强制转换和类型检查。
关于javascript - GWT JsType 数组转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49116169/