如何在GWT项目中将JSON转换为Java对象,反之亦然?

时间:2013-01-16 10:09:39

标签: json rest gwt

我使用GWT作为客户端应用程序和REST Web服务而不是服务器(不使用GWT中的RPC或servlet)。我想将java对象转换为JSON,并将JSON对象从客户端传递到服务器,也将服务器传递给客户端。但是对于处理我想将JSON对象转换为java对象i服务器。 GSON不支持GWT有没有办法将java对象转换为JSON对象,反之亦然?

我使用Autobean框架将一个示例项目转换为JSON,但是我收到了以下错误

[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?)

以下是我的代码

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);

            }
        });
    }
}

1 个答案:

答案 0 :(得分:13)

有没有办法将java对象转换为JSON对象,反之亦然?

您可以使用GWT的autobean框架。它可以在服务器和客户端双方使用。

示例:

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();   
}