0

I want to pass an object from the server to the client with Vaadin:

My object:

public class MyObject {
    public String name;
    public int value;
}

Then I have a component extending AbstractJavaScriptComponent, which has this:

public void doStuff(MyObject obj) {
    callFunction("doStuff", obj);
}

The JavaScript function doStuff is then correctly called, but the argument I get doesn't have the properties name and value, the type of the argument is correct (MyObject).

MyObject is part of the WidgetSet (it is in the *.client namespace), though I don't know if that is even a must..

What's going wrong?

Erpel
  • 150
  • 1
  • 8

3 Answers3

1

Well just for reference, I'll answer it myself:

Even though callFunction says that it can handle Objekts/JavaBeans, it seems to me that it actually cannot. But this way it works:

Put something like this in your WidgetSet:

public interface MyComponentClientRpc extends ClientRpc {
    public void doStuff(MyObject obj);
}

Then instead of callFunction use getRpcProxy(MyComponentClientRpc.class).doStuff(obj);

And put something like this in your JS-Connector:

this.registerRpc({
    doStuff : function(obj) {
        alert(obj);
    },
});

I learned about it here: https://vaadin.com/de/wiki/-/wiki/Main/Using%20complex%20Java%20types%20from%20JavaScript

Erpel
  • 150
  • 1
  • 8
0

callFunction utilizes the underline JSON marshal/unmarshal mechanism. So you should make your transport object to implement "org.json.JSONString" interface. 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);
    }
}
0

I have just debugged into the code.

The problem is that callFunction() accepts an Object[]. Thus the type that the JsonCodec gets as a hint is Object.class and not the type of the items in the Object[].

I found out a dirty workaround for now:

MyOptions options = new MyOptions();
options.foo = "bar";
options.count = 1;
callFunction("myFunction",
             JsonCodec.encode(options , null, MyOptions.class, null).getEncodedValue())
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Frithjof Schaefer
  • 1,135
  • 11
  • 22