2012-10-08 1 views
2

J'essaie de lire les données XML d'un service (et je ne peux pas changer les données) et j'ai un problème avec le Jackson XmlMapper. Si je XML comme ceci:Jackson XmlMapper Conversion de XML en POJO, la clé du texte de nœud est ""

<entry> 
    <title type="text">W411638</title> 
</entry> 

Il me donne de nouveau la carte suivante:

title: ["": "W411638", "type": text] 

Je suis en train de transformer cela en un objet en utilisant le code suivant:

XmlMapper xmlMapper = new XmlMapper() 
Entry entry = xmlMapper.readValue(xmlData, Entry.class) 

Et ma classe d'entrée ressemble à:

class Entry { 
    static class Title { 
     //String __; //-- This is what I can't figure out -- 
     String type; 
    } 

    Title title; 
} 

Le problème est que je ne trouve aucun moyen d'obtenir ce texte de titre ("W411638") dans l'objet d'entrée. Le type tire bien et je peux l'obtenir en faisant entry.title.type et c'est correct, je ne sais pas comment obtenir cette valeur de titre.

Répondre

2

Cela fonctionne pour moi comme un script Groovy autonome ...

@Grab('com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.0.5') 
import com.fasterxml.jackson.dataformat.xml.XmlMapper 
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlText 

class Entry { 
    static class Title { 
    public String type 

    @JacksonXmlText 
    public String value 

    public String toString() { 
     "$type -> $value" 
    } 
    } 

    public Title title 

    public String toString() { 
    "Entry [$title]" 
    } 
} 

def xml = '''<entry> 
      | <title type="text">W411638</title> 
      |</entry>'''.stripMargin() 

def xmlMapper = new XmlMapper() 
Entry pojo = xmlMapper.readValue(xml, Entry) 

println pojo // prints 'Entry [text -> W411638]' 

Croisons les doigts ça marche pour vous aussi!

+0

Oui, c'est la façon dont il devrait fonctionner. – StaxMan

+0

Cela fonctionne, merci !! – Tim

2

J'ai pu résoudre ce problème en utilisant @JSONCreator ainsi;

xml

<x> 
    <a b="c" d="e">CDATA Text</a> 
</x> 

X.java

public class A 
{ 
    private B b; 
    private D d; 
    private String cdata; 

    @JsonCreator 
    public PropertyDef(Map<String,Object> props) 
    { 
     setB((String) props.get("b")); 
     setD((String) props.get("d")); 
     setCdata((String) props.get("")); 
    } 
} 
Questions connexes