-1

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..!

Ajinkya
  • 111
  • 1
  • 3
  • 13

2 Answers2

1

GWT ain't able to convert Java objects into JavaScript objects.

But if you let your Student class extend the JavaScriptObject. You can then work with the Student class in both the native JavaScript world and the GWT world.

One other way is to create a method that creates a JSONObject and fills it with data from the Student class.

    JSONObject j = new JSONObject();
    j.put("firstName", new JSONString(firstName()));
    j.put("lastName", new JSONString(lastName()));
    return j; // or return j.toString();
Lacke
  • 61
  • 2
0

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.

Braj
  • 46,415
  • 5
  • 60
  • 76
  • Does autobean supports List and map also? – Ajinkya Apr 11 '14 at 11:12
  • Look at this section `JSON structures` mentioned at above link or [click here](http://code.google.com/p/google-web-toolkit/wiki/AutoBean#visitCollectionProperty%28%29_/_visitMapProperty%28%29) – Braj Apr 11 '14 at 11:58