【问题标题】:How can you use GWT AutoBeans to parse a JSON message when some of the return values could be an object or a collection of objects?当某些返回值可能是对象或对象集合时,如何使用 GWT AutoBeans 解析 JSON 消息?
【发布时间】:2012-11-28 14:53:27
【问题描述】:

当返回的对象之一可能是集合但并非总是如此时,是否可以使用 GWT AutoBeans 解析 JSON 消息?

例如,如果我有一条返回作者及其相关著作的 JSON 消息,则返回的书籍可能为零或多本。

{ "name" : "William Gibson", "books" : { bookname : "Neuromancer" } }

可能是一种回应,但也可能是这样:

{ "name" : "William Gibson", "books" : [ { bookname: "Neuromancer"}, { bookname : "Pattern Recognition" } ] }

当我尝试使用用于编组 AutoBean 的接口对此进行建模时,如果只返回一本书,我会收到“期望索引数据”错误。

AutoBean 的接口:

public interface Author {
  @PropertyName(value="name")
  String getAuthorName();
  @PropertyName(value="book")
  List<String> getBooks();
}

错误片段:

java.lang.AssertionError: Expecting indexed data
at com.google.web.bindery.autobean.shared.impl.SplittableList.<init>(SplittableList.java:64)

AutoBeans 不能做到这一点吗?

(注意:使用 GWT 2.5.0 GA)

【问题讨论】:

    标签: json parsing gwt autobean


    【解决方案1】:

    如果您有一个List,AutoBeans 需要一个 JSON 数组。该数组可以包含零个、一个或多个元素,但它必须是一个数组(或不存在)。

    我认为你可以让你的getBooks 方法返回一个Splittable。然后您就可以知道它是否是一个数组 (isIndexed())。如果您需要数组包含对象,则必须迭代数组(size()get(int))并将每个元素传递给 AutoBeanCodex.decode() 以对其进行解码(或者如果它不是数组,则直接传递可拆分表)。

    【讨论】:

    • 好的,但是如果我无法控制 JSON 消息本身(例如,我不能将它强制转换为 n 个元素的数组格式),是否无法以它可以处理的方式对 AutoBean 进行建模什么时候只返回一个元素?
    • 我认为您可以使用Splittable 属性类型;查看编辑后的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-01
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 2012-11-02
    • 1970-01-01
    • 2022-01-26
    相关资源
    最近更新 更多