Reputation: 2445
I am using a GWT for client side application and REST web service instead of server(not using RPC or servlets in GWT). I want to convert java object to JSON and pass JSON object from client to server and also server to client. But for processing I want to convert JSON object to java object i server. GSON is not supporting by GWT is there any way to convert java object to JSON object and vice versa?
I did a sample project using Autobean framework for converting java object to JSON , but I got the following error
[ERROR] [gwtmodules] - Deferred binding result type 'com.mycompany.gwtmodules.client.MyFactory' should not be abstract
] Failed to create an instance of 'com.mycompany.gwtmodules.client.Gwtmodules' via deferred binding
java.lang.RuntimeException: Deferred binding failed for 'com.mycompany.gwtmodules.client.MyFactory' (did you forget to inherit a required module?)
Following is my code
public interface Test {
public int getAge();
public void setAge(int age);
public String getName();
public void setName(String name);
}
import com.google.web.bindery.autobean.shared.AutoBean;
import com.google.web.bindery.autobean.shared.AutoBeanFactory;
public interface MyFactory extends AutoBeanFactory{
AutoBean<Test> test();
}
public class Gwtmodules implements EntryPoint {
MyFactory factory = GWT.create(MyFactory.class);
/**
* This is the entry point method.
*/
Test makeTest() {
// Construct the AutoBean
AutoBean<Test> test = factory.test();
// Return the Person interface shim
return test.as();
}
Test deserializeFromJson(String json) {
AutoBean<Test> bean = AutoBeanCodex.decode(factory, Test.class, json);
return bean.as();
}
String serializeToJson(Test test) {
// Retrieve the AutoBean controller
AutoBean<Test> bean = AutoBeanUtils.getAutoBean(test);
return AutoBeanCodex.encode(bean).getPayload();
}
public void onModuleLoad() {
final Test test = makeTest();
test.setAge(44);
test.setName("achu");
final Button button = new Button("Click here");
button.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
String s = serializeToJson(test);
Window.alert("alert" + s);
}
});
}
}
Upvotes: 3
Views: 8212
Reputation: 7630
is there any way to convert java object to JSON object and vice versa?
You can use autobean framework of GWT. It can be used at server and client both side.
Example:
String serializeToJson(Test test)
{
// Retrieve the AutoBean controller
AutoBean<Test> bean = AutoBeanUtils.getAutoBean(test);
return AutoBeanCodex.encode(bean).getPayload();
}
Test deserializeFromJson(String json)
{
AutoBean<Test> bean = AutoBeanCodex.decode(myFactory, Test.class, json);
return bean.as();
}
Upvotes: 14