简单的XML反序列化

时间:2013-10-22 15:05:01

标签: java android parsing simple-framework serializer

为什么这会返回“null”?它应该返回“Beedrill& Bug”......

Data.java:

package com.example.pokemon;

import java.io.Serializable;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;

@Root(name="Data", strict=false)
public class Data implements Serializable {

    public Data() {}

    @Element(name = "nm", required=false)
    private String nm;

    public String gtNm(){
        return nm;
    }
    @Element(name = "tp", required=false)
    private String tp;

    public String gtTp(){
        return tp;
    }
}

data.xml中:

<?xml version = "1.0" encoding = "utf-8" ?>

<Data>

    <Pokemon> 
        <nm>Beedrill</nm> 
        <tp>bug</tp> 
        <ablt>swarm</ablt>
        <wkns>fire</wkns>
        <img>beedrill</img>
    </Pokemon> 


</Data>

MainActivity.java:

    try {
        Serializer serializer = new Persister();
        AssetManager assetManager = getAssets();
        InputStream inputStream = assetManager.open("data.xml");
        Data d = serializer.read(Data.class, inputStream);
        System.out.println("[JOE]: It worked! "+d.gtNm());
        System.out.println("[JOE]: It worked! "+d.gtTp());
    } 
    catch (Exception e) {
        e.printStackTrace();
        System.out.println("[JOE]: error! "+e.getMessage());
    }

LogCat:

[JOE]: It worked! null
[JOE]: It worked! null

1 个答案:

答案 0 :(得分:2)

您的xml树是......

<Data>
    <Pokemon> 
        <nm>Beedrill</nm> 

这意味着,在数据中需要以下内容,因为口袋妖怪是数据的元素,而Nm是口袋妖怪的属性。

   @Element
   private Pokemon pokemon;

然后你需要创建一个名为Pokemon的类,它具有你在Data中指定的属性,这样你就可以d.getPokemon().gtNm();

按照&#34;嵌套对象序列化&#34;

下的示例here