使用SimpleFramework

时间:2015-07-04 20:21:03

标签: java android xml simple-framework

我正在尝试使用SimpleFramework反序列化此XML数组,并且我一直遇到此问题:

  

07-04 16:14:59.840 1681-1681 / com.sampleapp D / SampleApp:org.simpleframework.xml.core.ElementException:Element' image'在第5行的com.todocodepathapp.api.models.Images类中没有匹配项

这是从API返回的xml数组:

<response>
<data>
    <images>
        <image>
            <url>http://24.media.tumblr.com/tumblr_lmdpfs0UcO1qbe5pxo1_1280.jpg</url>
            <id>9ik</id>
            <source_url>http://thecatapi.com/?id=9ik</source_url>
        </image>
        <image>
            <url>http://25.media.tumblr.com/tumblr_m6nl30dMm21qz59j6o1_1280.jpg</url>
            <id>MTU4NTM4NA</id>
            <source_url>http://thecatapi.com/?id=MTU4NTM4NA</source_url>
        </image>
        <image>
            <url>http://25.media.tumblr.com/tumblr_m1e6655aqv1qz85pko1_500.jpg</url>
            <id>avd</id>
            <source_url>http://thecatapi.com/?id=avd</source_url>
        </image>
        <image>
            <url>http://24.media.tumblr.com/tumblr_lz7cx55fOS1qbd47zo1_1280.jpg</url>
            <id>cu8</id>
            <source_url>http://thecatapi.com/?id=cu8</source_url>
        </image>
    </images>
</data>
</response>

这些是我正在使用的模型类(我有预感,我不应该使用 Images.java ,并且应该只有三个类):

Response.java

@Root(name = "response")
public class Response {

    @Element(name = "data")
    private Data mData;
    public Data getData() {
    return mData;
    }

}

Data.java

@Root(name = "data")
public class Data {

    @Element(name = "images")
    private Images mImages;
    public Images getImages() {
        return mImages;
    }

}

Images.java

@Root(name = "images")
public class Images {

    @ElementList(entry = "image")
    private List<Image> mImageList;
    public List<Image> getImageList() {
        return mImageList;
    }

}

Image.java

@Root(name = "image")
public class Image {

    @Element(name = "url")
    private String mUrl;
    public String getUrl() {
        return mUrl;
    }

    @Element(name = "id")
    private String mId;
    public String getId() {
        return mId;
    }

    @Element(name = "source_url")
    public String mSourceUrl;
    public String getSourceUrl() {
        return mSourceUrl;
    }

}

我应该如何完成这项工作?我认为用条目@ElementList(entry = "image")添加注释会解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

我的预感是正确的,我继续删除了课程Images.java并将以下注释添加到我的Data.java模型类中:

@ElementList(name = "images", entry = "image")
private List<Image> mImages;
public List<Image> getImages() {
    return mImages;
}

需要注意的是,我为Image模型类更改了@Root@Element

@Element(name = "image")
public class Image {

    @Element(name = "url")
    private String mUrl;
    public String getUrl() {
        return mUrl;
    }

    @Element(name = "id")
    private String mId;
    public String getId() {
        return mId;
    }

    @Element(name = "source_url")
    public String mSourceUrl;
    public String getSourceUrl() {
        return mSourceUrl;
    }

}