【问题标题】:GWT Autobean - how to handle lists?GWT Autobean - 如何处理列表?
【发布时间】:2012-11-30 18:35:19
【问题描述】:

我一直在尝试评估 GWT Autobean 功能以将 JSON 对象解码/编码为域对象以进行 REST 调用。

以下示例:http://code.google.com/p/google-web-toolkit/wiki/AutoBean#Quickstart

我能够将单个 JSON 对象转换为域对象:

AutoBean<Person> personBean = AutoBeanCodex.decode(factory, Person.class, JsonResources.INSTANCE.json().getText());

其中 JsonResources.INSTANCE.json() 返回一个 JSON 字符串。

但是,我没有成功从 JSON 转换 Person 对象列表。

如果有人有这方面的例子,会很有帮助吗?

谢谢!

【问题讨论】:

    标签: json gwt autobean


    【解决方案1】:

    嗯,我能想到的唯一方法是创建一个特殊的 autobean,它将具有 List&lt;Person&gt; 属性。例如:

    public interface Result {
        void setPersons(List<Person> persons);
        List<Person> getPersons();
    }
    

    以及示例 json 字符串:

    {
       persons:[
          {"name":"Thomas Broyer"},
          {"name":"Colin Alworth"}
       ]
    }
    

    更新: 输入 JSON 是数组时的解决方法(如 cmets 中的 persons[0] 所建议)。例如JSON 看起来像这样:

    [{"name":"Thomas Broyer"},{"name":"Colin Alworth"}]
    

    解析代码如下:

    AutoBeanCodex.decode(factory, Result.class, "{\"persons\": " + json + "}").getPersons();
    

    【讨论】:

    • 在不更改 JSON 的情况下解决该问题:AutoBeanCodex.decode(factory, Result.class; "{\"persons\": " + json + "}").getPersons()
    • 这是我在我的 autobeans 中使用的技术。但我想我会应用@ThomasBroyer 提出的技术。
    • @ThomasBroyer 好主意,我已将其添加到答案中,因为您的代码中有一点拼写错误。
    • 感谢您的回答。问题是我有一堆接口。我不想为它们中的每一个或每次添加新的时都这样做。一般有没有办法做到这一点?有什么想法吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多