Wednesday, September 5, 2012

GWT - JSNI , Facing error while using String[] as return type.

I worked with JSON and JSNI to retrieve data from server and sending the data back to client. The server returns the following JSON as a response to a request   


[{"message": "MMMM","word": "abcd","options": ["I","H","G","F","E"],"answer": 0}]

My class that results in by the eval(json) function is the following

public class Question extends JavaScriptObject{
      
    protected Question() {
    }
      
    public final native String getMessage()/*-{ return this.message ; }-*/;
    public final native String getWord()/*-{ return this.word ; }-*/;               
    public final native String[] getOptions()/*-{ return this.options ; }-*/;
    public final native int getAnswer()/*-{ return this.answer ; }-*/;
    

}


then calling the getOptions() function inside the code greeted me with the following exception

java.lang.ClassCastException: com.google.gwt.core.client.JavaScriptObject$ cannot be cast to [Ljava.lang.String

After that I changed 
public final native String[] getOptions()/*-{ return this.options ; }-*/;
to
public final native JsArrayString getOptions()/*-{ return this.options ; }-*/;

and make necessary update in code to work with JsArrayString ( It is more or less like ArrayList in java ) . Then the code worked nicely.