Search code examples
javascriptjsongwtjsni

Convert java object into json by using javascript native function in gwt


I want to convert my java object into json by using JSNI i.e javascript native method in GWT. I dont want to use any external jar like Gson, jackson. I have dove following code.

public class JsonToJavaUsingJS implements EntryPoint {

  final Student student = new Student(5, "ajinkya", "patil");

  @Override
  public void onModuleLoad() {

    toJson(student);
  }

  public native void toJson(final Student student)
  /*-{
    var json = JSON.stringify(student);
    alert("json object: " + json);
  }-*/;
  }

but It does not convert java object into json string. It gives follwing exception

[ERROR] [jsontojavausingjs] - Uncaught exception escaped com.google.gwt.event.shared.UmbrellaException: Exception caught: (null) @com.json.js.client.JsonToJavaUsingJS::toJson(Lcom/json/js/client/Student;)([Java object: com.json.js.client.Student@176073104]): null

plese help..!


Solution

  • I suggest you first try with GWT way if nothing found then go down to native JavaScript way.

    A simple way is defined here GWT AutoBean framework along with quick start and samples.

    Read more about Sharing objects between Java source and JavaScript.