2013-10-22 52 views
0

爲什麼返回「null」?它應該返回 「Beedrill &蟲」 ......簡單的XML反序列化

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 

回答

2

你的XML樹是...

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

這意味着,你需要的數據下面的口袋妖怪是數據的一個元素和NM是寵物小精靈的屬性。

@Element 
    private Pokemon pokemon; 

然後,您需要創建一個名爲口袋妖怪類,它有你在數據中指定的屬性,這樣一來,就可以d.getPokemon().gtNm();

按照「嵌套對象序列化」下的示例here