有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java阅读列表<Item>,从XML API进行了改进

我正在尝试使用SimpleXmlConverter的改进从我的API读取数据

我的课堂评论如下:

@Root
class Comment {
  @Element
  private String text;
}    

我想阅读XML中的注释列表:

<comments>
  <comment>
    <text>sample text</text>
  </comment>
  <comment>
    <text>sample text</text>
  </comment>
</comments>

在我的界面中有一个方法:

@GET("/lastcomments")
ArrayList<Comment> lastComments();

但当我调用lastComments()时,改型抛出:

 Caused by: retrofit.RetrofitError: java.lang.ClassCastException: libcore.reflect.ParameterizedTypeImpl cannot be cast to java.lang.Class
        ...
 Caused by: retrofit.converter.ConversionException: java.lang.ClassCastException: libcore.reflect.ParameterizedTypeImpl cannot be cast to java.lang.Class
        at com.mobprofs.retrofit.converters.SimpleXmlConverter.fromBody(SimpleXmlConverter.java:76)
        ...
 Caused by: java.lang.ClassCastException: libcore.reflect.ParameterizedTypeImpl cannot be cast to java.lang.Class
        at com.mobprofs.retrofit.converters.SimpleXmlConverter.fromBody(SimpleXmlConverter.java:72)

是否可以直接从API读取列表,或者我必须创建包装器:

@Root(name="comments")
class CommentsList {
  @Element(name="comment", inline=true)
  List<Comment> comments;
}

共 (2) 个答案

  1. # 1 楼答案

    您需要使用CommentList类。接口应为:

    @GET("/lastcomments")
    CommentList lastComments();
    

    用于同步呼叫或

    @GET("/lastcomments")
    void lastComments(Callback<CommentList> callback);
    

    用于异步调用

  2. # 2 楼答案

    对不起,我知道这可能太晚了,但以下是答案:

    您需要使用ElementList属性:

    @Root(name="comments")
    class CommentsList {
        @ElementList(name="comment")
        List<Comment> comments;
    }