Domanda

Can anyone tell me why my deserializer isn't working?

Main.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]: "+d.getPokemon().getName());
    } 
    catch (Exception e) {
        e.printStackTrace();
        System.out.println("[JOE] error:  "+e.getMessage());
    }

data.xml:

<Data>

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

</Data>

Pokemon.java:

package com.example.pokemon;

import java.io.Serializable;

import org.simpleframework.xml.Element;
//import org.simpleframework.xml.Element;
public class Pokemon implements Serializable{

    @Element
    private String name;
    @Element
    private String type;
    @Element
    private String abilities;
    @Element
    private String weakness;
    @Element
    private String image;

    public Pokemon(){}
    public Pokemon(String n, String t, String a, String w, String i){
        name = n;
        type = t;
        abilities = a;
        weakness = w;
        image = i;
    }
    public String getName(){
        return name;
    }
}

Data.java:

import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;

@Root(name="Data", strict=false)
public class Data {
    @Element 
    private Pokemon pokemon;

    public Pokemon getPokemon() {
        return pokemon;           
    }
}

Stack Trace:

Stack_trace

È stato utile?

Soluzione

Well, there are a couple of things worth pointing out here:

Firstly, you've annotated the pokemon field in the Data class, but this is not going to work unless you supply the name of the xml tag the field should be bound up to. SimpleXML won't know that you actually mean the bind up Pkmn to pokemon. In short, add:

@Element(name="Pkmn") private Pokemon pokemon;

Last time I checked, SimpleXML does support auto-binding, but that will require the @Default annotation and the field names have to match the xml tags.

That being said, the safest option here is to not use @Default and explicitly supply the name with every annotation. That is, go through your Pokemon class and declare the name for every @Element annotation. For example:

...
@Element(name="ablt") private String abilities;
...

After that, you should be close to have working code. To clean up, you may want to remove strict=false from the @Root declaration of your Data class. That was probably your initial attempt to bypass the ValueRequiredException? If the Data tag not having a Pkmn tag is a valid scenario, then potentially leave it in there, but otherwise you should remove it to avoid undesired side effects.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top