[Java] GWT with JSON 2 AutoBean

博客首页 » Java GWT with JSON 2 AutoBean

发布于 24 Dec 2014 16:14
标签 blog
上一次,我们讲述了GWT中使用JSON的基本实现——org.json,这一次我们把demo修改成AutoBean。可以看到虽然这里只有很小的差别,但是AutoBean比json原始实现要简便许多。

gwt.xml中添加引用

<inherits name="com.google.web.bindery.autobean.AutoBean"/>

Shared Classes

在公共类中添加输入、输出的bean和factory

public interface GreetingInput {
    String getName();
    void setName(String name);
}
public interface GreetingOutput {
    String getResult();
    void setResult(String result);
}
import com.google.web.bindery.autobean.shared.AutoBean;
import com.google.web.bindery.autobean.shared.AutoBeanFactory;
 
public interface GreetingAutoBeanFactory extends AutoBeanFactory {
    AutoBean<GreetingInput> greetingInput();
    AutoBean<GreetingInput> greetingInput(GreetingInput input);
    AutoBean<GreetingOutput> greetingOutput(GreetingOutput output);
}
Client GreetingServiceAsync

在将类转化成Json的时候,只需要从factory中取得autobean<T>,然后再用as去出来赋值,接着用AutoBeanCodex.encode(bean).getPayLoad()来取得编码的JSON字符串。

    private final GreetingServiceAsync greetingService = new GreetingServiceAsync() {
        @Override
        public void greetServer(String name, final AsyncCallback<String> callback)
                throws IllegalArgumentException {
 
            AutoBean<GreetingInput> input = factory.greetingInput();
            input.as().setName(name);
 
            //JSONObject inputs = new JSONObject();
            //inputs.put("name", new JSONString(name));
 
            RequestBuilder builder = 
                    new RequestBuilder(RequestBuilder.POST, 
                    GWT.getModuleBaseURL()+ "greetJson"
                    );
 
            try {
                builder.sendRequest(AutoBeanCodex.encode(input).getPayload(), //inputs.toString() 
                        new RequestCallback(){
                    @Override
                    public void onResponseReceived(Request request,
                            Response response) {
                        JSONValue rst = JSONParser.parseStrict(response.getText());
                        callback.onSuccess(response.getText());
                    }
                    @Override
                    public void onError(Request request, Throwable exception) {
                        callback.onFailure(exception);
                    }});
            } catch (RequestException exception) {
                callback.onFailure(exception);
            }
        }};
Client的onSuccess

使用AutoBeanCodex.decode可以将JSON字符串直接转化成AutoBean,然后用AutoBean.as转化成可操作对象。
GreetingOutput rst = AutoBeanCodex.decode(factory, GreetingOutput.class, result).as();

                greetingService.greetServer(textToServer,
                        new AsyncCallback<String>() {
                            public void onFailure(Throwable caught) {
                                // Show the RPC error message to the user
                                dialogBox
                                        .setText("Remote Procedure Call - Failure");
                                serverResponseLabel
                                        .addStyleName("serverResponseLabelError");
                                serverResponseLabel.setHTML(SERVER_ERROR);
                                dialogBox.center();
                                closeButton.setFocus(true);
                            }
 
                            public void onSuccess(String result) {
                                dialogBox.setText("Remote Procedure Call");
                                serverResponseLabel
                                        .removeStyleName("serverResponseLabelError");
 
                                GreetingOutput rst = AutoBeanCodex.decode(factory, GreetingOutput.class, result).as();
                                /*
                                JSONValue resultParse = JSONParser.parseStrict(result);
                                JSONValue resultVal = resultParse.isObject().get("result");
                                String name = resultVal.isString().stringValue();
                                */
                                String name = rst.getResult();
                                serverResponseLabel.setHTML(name);
 
                                dialogBox.center();
                                closeButton.setFocus(true);
                            }
                        });
Server Side
  • 从JSON到AutoBean的转换

为了使用AutoBean,我们需要用下面的AutoBeanFactorySource.create得到factory
GreetingAutoBeanFactory factory = (GreetingAutoBeanFactory) AutoBeanFactorySource.create(GreetingAutoBeanFactory.class);

然后使用AutoBeanCodex.decode得到AutoBeany以及Interface Bean。
GreetingInput input = AutoBeanCodex.decode(factory, GreetingInput.class, inputStr).as();

这样,就有一个可以操作的Interface Bean了。

  • 从AutoBean转换到JSON

首先对Interface Bean操作。

然后用AutoBeanUtils.getAutoBean从Interface Bean得到AutoBean。
AutoBeanUtils.getAutoBean(output)

接着就可以用AutoBeanCodex.encode得到转化后的JSON。
String result = AutoBeanCodex.encode(autoBean).getPayload();

    @Override
    public String greetServer(String inputStr) throws IllegalArgumentException {
        try {
            System.out.println("Received payLoad");
            GreetingAutoBeanFactory factory = (GreetingAutoBeanFactory) AutoBeanFactorySource.create(GreetingAutoBeanFactory.class);
            GreetingInput input = AutoBeanCodex.decode(factory, GreetingInput.class, inputStr).as();
            //JSONObject inputs = (JSONObject)new JSONTokener(inputStr).nextValue();
            //String name = inputs.getString("name");
            GreetingOutput output = factory.greetingOutput().as();
            output.setResult(escapeJsonHtml(input.getName()));
            String result = AutoBeanCodex.encode(AutoBeanUtils.getAutoBean(output)).getPayload();
 
            //String result = "{\"result\":\"" + escapeJsonHtml(name) + "\"}"; //" + escapeJson(name) + "
            return result;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

本页面的文字允许在知识共享 署名-相同方式共享 3.0协议和GNU自由文档许可证下修改和再使用,仅有一个特殊要求,请用链接方式注明文章引用出处及作者。请协助维护作者合法权益。


系列文章

文章列表

  • Java GWT with JSON 2 AutoBean

这篇文章对你有帮助吗,投个票吧?

rating: 0+x

留下你的评论

Add a New Comment
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License