2015-06-04 18 views
7

Sto usando MOXy 2.6 (JAXB + JSON).Evitare la creazione di tipo/valore wrapper oggetto in MOXy (JAXB + JSON)

Voglio ObjectElement e StringElement essere marshalling allo stesso modo, ma MOXy crea l'oggetto wrapper quando i campi vengono digitati come Object.

ObjectElement.java

public class ObjectElement { 
    public Object testVar = "testValue"; 
} 

StringElement.java

public class StringElement { 
    public String testVar = "testValue"; 
} 

Demo.java

import javax.xml.bind.JAXBContext; 
import javax.xml.bind.Marshaller; 

import org.eclipse.persistence.jaxb.JAXBContextFactory; 
import org.eclipse.persistence.jaxb.MarshallerProperties; 
import org.eclipse.persistence.oxm.MediaType; 

public class Demo { 

    public static void main(String[] args) throws Exception { 
     JAXBContext jc = JAXBContextFactory.createContext(new Class[] { ObjectElement.class, StringElement.class }, null); 
     Marshaller marshaller = jc.createMarshaller(); 
     marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_JSON); 

     System.out.println("ObjectElement:"); 
     ObjectElement objectElement = new ObjectElement(); 
     marshaller.marshal(objectElement, System.out); 
     System.out.println(); 

     System.out.println("StringElement:"); 
     StringElement stringElement = new StringElement(); 
     marshaller.marshal(stringElement, System.out); 
     System.out.println(); 
    } 

} 

Quando si lancia Demo.java, ecco l'output ...

ObjectElement: 
{"testVar":{"type":"string","value":"testValue"}} 
StringElement: 
{"testVar":"testValue"} 

Come configurare Moxy/JAXB per rendere ObjectElement rendere come oggetto StringElement? Come evitare la creazione di object wrapper con "type" e "value" proprietà?

risposta

2

è possibile utilizzare l'Annotazione javax.xml.bind.annotation.XmlAttribute. Questo renderà ObjectElement e StringElement sullo stesso output.

vedere l'esempio seguente:

import javax.xml.bind.annotation.XmlAttribute; 

public class ObjectElement { 
    @XmlAttribute 
    public Object testVar = "testValue"; 
} 

Ho usato il seguente test class per verificare il comportamento corretto.

EDIT dopo che la questione è stata aggiornata:

Sì, è possibile. Invece di usare XmlAttribute come prima, sono passato a javax.xml.bind.annotation.XmlElement in combinazione con un attributo type.

la classe viene ora dichiarato come:

public class ObjectElement { 
    @XmlElement(type = String.class) 
    public Object testVar = "testValue"; 
} 
+0

Avete qualche altra soluzione? Vorrei che funzionasse anche con XML senza creare un attributo, ma valore per essere contenuto di testo di testValue. – Toilal

+0

sì è possibile. guarda la mia risposta aggiornata e il codice di esempio su github. –