GWT JSNI中如何将JavaScript返回值转换为Java类型?遇转换问题求助
Hey there, let's sort out this null return value problem you're facing—it's not about the method being parameterless at all, so we can rule that out right away. Here's what's going on and how to fix it:
The Root Cause
Your someJSFunc() returns a JavaScript object ({ abc:xcv, def:asd }), but you're trying to convert it to a Java String using "" + $wnd.someJSFunc() + "". GWT's JSNI has strict type mapping rules: when you attempt to return a JS object as a Java String, GWT doesn't recognize it as a valid string type, so it returns null instead of the string representation you expected. The console.log works because it's natively handling the JS object, but the JSNI boundary between JS and Java is pickier about types.
The Fix: Serialize the JS Object to JSON
To properly pass the JS object's data to Java as a String, you need to serialize the object to a JSON string using JavaScript's built-in JSON.stringify() method. This converts the JS object into a standard string that GWT can safely map to a Java String.
Here's your updated JSNI method:
public static native String nativeJSFuncGwt() /*-{ const jsObj = $wnd.someJSFunc(); $wnd.console.log(jsObj); // Serialize the JS object to a JSON string return $wnd.JSON.stringify(jsObj); }-*/;
What to Do Next (If Needed)
If you want to work with the data as a Java object instead of just a string, you can use GWT's JSON parsing utilities to convert the JSON string into a Java-friendly structure. For example:
String tokenFromNativeJS = nativeJSFuncGwt(); JSONValue jsonValue = JSONParser.parseStrict(tokenFromNativeJS); JSONObject jsonObj = jsonValue.isObject(); // Access values like: String abcValue = jsonObj.get("abc").isString().stringValue();
Quick Note on the "No Parameters" Concern
Just to confirm: the lack of parameters in your JSNI method has zero impact on the return value issue. Your method was successfully calling someJSFunc() (evidenced by the console log), so parameter count isn't the problem here—it was purely a type conversion mismatch across the JS-Java boundary.
内容的提问来源于stack exchange,提问作者Raghvendra Kumar

