Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize / unmarshal generic list from XML to list in Android

I made a webservice in java with a method that returns a string (a generic list in XML format). I consume this webservice from Android, and I get this string, but after several tries the Android emulator just crashes when trying to deserialize the string. This is an example for the string I get:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<peliculas>
    <pelicula>
        <id>18329</id>
        <poster>http://cache-cmx.netmx.mx/image/muestras/5368.rrr.jpg</poster>
        <titulo>007 Operaci&amp;oacute;n Skyfall</titulo>
    </pelicula>
...
</peliculas>

This is the class in the webservice:

@XmlRootElement
public class Peliculas{

    @XmlElement(name="pelicula")
    protected List<Pelicula> peliculas;
    public Peliculas(){ peliculas = new ArrayList<Pelicula>();}

    public Peliculas(List<Pelicula> pe){
        peliculas = pe;
    }


    public List<Pelicula> getList(){
        return peliculas;       
    }

    public void add(Pelicula pelicula) {
        peliculas.add(pelicula);
    }
}

________EDIT______________

Seems like you can't use JAXB with Android, and there's better/lighter libraries for that. so I tried Simple XML. This is the method:

public Peliculas unmarshal(String xml) throws Exception{            
    Peliculas peliculas = new Peliculas();  
    Serializer serializer = new Persister();
    StringBuffer xmlStr = new StringBuffer( xml );
    peliculas = serializer.read(Peliculas.class, ( new StringReader( xmlStr.toString() ) )  );
    return peliculas;
}

BUT I get this exception, seems like it can't save data in object:

11-12 20:30:10.898: I/Error(1058): Element 'Pelicula' does not have a match in class app.cinemexservice.Pelicula at line 3
like image 521
Pundia Avatar asked Nov 11 '12 20:11

Pundia


Video Answer


1 Answers

I think you are doing correct, Try this code which is given in the API.

JAXBContext jc = JAXBContext.newInstance( "add your class's full qualified class name here" );
Unmarshaller u = jc.createUnmarshaller();
Object o = u.unmarshal( xmlSource );

You can cast the Object o to your type I think. Please refer this. http://jaxb.java.net/nonav/2.2.4/docs/api/javax/xml/bind/Unmarshaller.html

like image 56
andunslg Avatar answered Sep 19 '22 23:09

andunslg