我想使用Vaadin将对象从服务器传递到客户端:
我的对象:
public class MyObject {
public String name;
public int value;
}
然后我有一个扩展AbstractJavaScriptComponent
的组件,其中包含:
public void doStuff(MyObject obj) {
callFunction("doStuff", obj);
}
然后正确调用JavaScript函数doStuff
,但我得到的参数没有属性name
和value
,参数的类型是正确的({{1 }})。
MyObject
是WidgetSet的一部分(它位于* .client命名空间中),但我不知道这是否是必须的..
出了什么问题?
答案 0 :(得分:0)
嗯,仅供参考,我会自己回答:
即使callFunction
说它可以处理Objekts / JavaBeans,但在我看来它实际上不能。
但这种方式有效:
在你的WidgetSet中添加这样的东西:
public interface MyComponentClientRpc extends ClientRpc {
public void doStuff(MyObject obj);
}
然后使用callFunction
getRpcProxy(MyComponentClientRpc.class).doStuff(obj);
在你的JS-Connector中添加这样的东西:
this.registerRpc({
doStuff : function(obj) {
alert(obj);
},
});
我在这里了解到了这一点:https://vaadin.com/de/wiki/-/wiki/Main/Using%20complex%20Java%20types%20from%20JavaScript
答案 1 :(得分:0)
callFunction使用下划线JSON marshal / unmarshal机制。所以你应该让你的传输对象实现“org.json.JSONString”接口。 e.g。
public class MyObject implements JSONString, Serializable {
public String name;
public int value;
@Override
public String toJSONString() {
return String.format("{\"name\":\"%s\",\"value\":%d}", name, value);
}
}
答案 2 :(得分:0)
我刚刚调试了代码。
问题是callFunction()
接受Object[]
。因此,JsonCodec作为提示获得的类型是Object.class
,而不是Object[]
中项目的类型。
我现在发现了一个肮脏的解决方法:
MyOptions options = new MyOptions();
options.foo = "bar";
options.count = 1;
callFunction("myFunction",
JsonCodec.encode(options , null, MyOptions.class, null).getEncodedValue())