1

I'm trying to parse a json string on client side using Gson but while installing project getting an error:

 No source code is available for type com.google.gson.Gson; did you forget to inherit a required module?

I have added <inherits name='com.google.gson.Gson' /> on my gwt.xml. I'm using GWT 2.8.1 can we use Gson on client side ?
[this][1]

using Gson library in GWT client code used older version of GWT and my question is also related to error of Gson module .

Prashant Palve
  • 132
  • 2
  • 11
  • Possible duplicate of [using Gson library in GWT client code](https://stackoverflow.com/questions/2213734/using-gson-library-in-gwt-client-code) – Lyubomyr Shaydariv May 28 '18 at 10:09
  • 1
    The error is pretty self-descriptive: client-scope GWT uses libraries source code to compile it to JavaScript. Also, GWT can only use a very limited set of JDK features, whilst Gson is built some advanced of them, therefore you *cannot* use Gson at the client side. – Lyubomyr Shaydariv May 28 '18 at 10:13

1 Answers1

5

Gson is not GWT compatible. You should use a GWT compatible library like gwt-jackson.

Alternatively, if your models are simple you can use a technique called JsInterop DTOs. And use the browser native JSON.parse function directly. This technique is based in JsInterop and some limitation explained here. Example:

@JsType(isNative = true, namespace = JsPackage.GLOBAL, name = "Object") 
class SearchResult {
    public String display_name; //ex: "Málaga, Provincia de Málaga, Andalusia, Spain"
    public String lat, lon; //ex: lat: "36.7210805", lon: "-4.4210409"
    public double importance; //ex: 0.73359836669253
}

And then call native parse (need to import elemental2-core library):

Object jsonObj = elemental2.core.Global.JSON.parse(jsonStr);
SearchResult result = jsinterop.base.Js.cast(jsonObj);
Ignacio Baca
  • 1,538
  • 14
  • 18
  • This chat room is a pretty good place if you are not sure what is the best option for your specific use case https://gitter.im/gwtproject/gwt/. GWT has too many options and it is super frequently to get confused, so go to the chat and discuss your case! – Ignacio Baca May 28 '18 at 11:26
  • Thanks @Ignacio Baca ,JSON.parse() is working in my case,actually i won't need to use JsInterop. to use object i have used public static native String getObject(String jsVar)/*-{ return eval('$wnd.' + jsVar); }-*/; – Prashant Palve May 28 '18 at 12:30
  • 1
    That's the old way, ;) JsInterop is the new strategy, much clean and future proof! Strongly recommended – Ignacio Baca May 28 '18 at 12:45