É possível conseguir desfazer / organizar uma estrutura de classe que utiliza o aninhamento de vários abstract
aulas?
Dada uma estrutura de classe como esta:
@XmlAccessorType(XmlAccessType.FIELD)
public abstract class Animal {}
public abstract class Mammal extends Animal {}
public class Tiger extends Mammal {}
public class Elephant extends Mammal {}
o @XmlRootElement
ed Zoo
classe tem uma lista de animais:
@XmlElementWrapper(name = "animals")
@XmlElements({
@XmlElement(name = "elephant", type = Elephant.class),
@XmlElement(name = "tiger", type = Tiger.class)
})
private List<Animal> animals;
Acho que você entendeu ... o XML para isso:
<?xml version="1.0" encoding="utf-8"?>
<zoo>
<animals>
<tiger>
<name>Richard</name>
<furry>true</furry>
</tiger>
<elephant>
<name>Otis</name>
<furry>false</furry>
</elephant>
<tiger>
<name>Kirk</name>
<furry>true</furry>
</tiger>
</animals>
</zoo>
Isso parece bom, legal.
Agora o JSON ...
{
"animals" : {
"tiger" : [ {
"name" : "Richard",
"furry" : true
}, {
"name" : "Kirk",
"furry" : true
} ],
"elephant" : [ {
"name" : "Otis",
"furry" : false
} ]
}
}
Por que subgrupo o Mammal
objetos de classe em JSON?
Estou usando EclipseLink MOXy 2.6 para empacotar.
Respostas:
1 para resposta № 1RESPOSTA ORIGINAL
MOXy agrupa as chaves tiger
e elephant
para evitar repeti-los.
ATUALIZAÇÃO # 1
Portanto, não é possível obter um JSON como {"animals": [{"@type": "tiger"}, {"@type": elephant "}, ...]}?
Sim, é possível, você só precisa mapeá-lo dessa forma:
Jardim zoológico
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)
public class Zoo {
private List<Animal> animals;
}
Animal
import javax.xml.bind.annotation.*;
@XmlSeeAlso({Elephant.class, Tiger.class})
@XmlAccessorType(XmlAccessType.FIELD)
public abstract class Animal {
}
Demonstração
import java.util.*;
import javax.xml.bind.*;
import javax.xml.transform.stream.StreamSource;
import org.eclipse.persistence.jaxb.JAXBContextProperties;
public class Demo {
public static void main(String[] args) throws Exception {
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(JAXBContextProperties.MEDIA_TYPE, "application/json");
properties.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false);
properties.put(JAXBContextProperties.JSON_ATTRIBUTE_PREFIX, "@");
JAXBContext jc = JAXBContext.newInstance(new Class[] {Zoo.class}, properties);
Unmarshaller unmarshaller = jc.createUnmarshaller();
StreamSource json = new StreamSource("src/forum19384491/input.json");
Zoo zoo = unmarshaller.unmarshal(json, Zoo.class).getValue();
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(zoo, System.out);
}
}
input.json/Output
{
"animals" : [ {
"@type" : "tiger"
}, {
"@type" : "elephant"
}, {
"@type" : "tiger"
} ]
}
ATUALIZAÇÃO # 2
Se você deseja manter sua representação XML atual e apenas alterar a representação JSON, você pode usar a extensão de documento de mapeamento externo do MOXy (consulte: http://blog.bdoughan.com/2010/12/extending-jaxb-representing-annotations.html)
Documento de mapeamento (oxm.xml)
Usaremos o documento de mapeamento externo do MOXy para alterar o mapeamento do animals
campo no Zoo
classe.
<?xml version="1.0"?>
<xml-bindings
xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
package-name="forum19384491">
<java-types>
<java-type name="Zoo">
<java-attributes>
<xml-element java-attribute="animals"/>
</java-attributes>
</java-type>
</java-types>
</xml-bindings>
Demonstração
No código de demonstração abaixo, criamos 2 instâncias de JAXBContext
no mesmo modelo de domínio. O para JSON utiliza um documento de mapeamento externo para personalizar o mapeamento. input.xml
é o documento XML de sua pergunta.
import java.io.File;
import java.util.*;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.JAXBContextProperties;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext xmlJC = JAXBContext.newInstance(Zoo.class);
Unmarshaller unmarshaller = xmlJC.createUnmarshaller();
File xml = new File("src/forum19384491/input.xml");
Zoo zoo = (Zoo) unmarshaller.unmarshal(xml);
Map<String, Object> properties = new HashMap<String, Object>(4);
properties.put(JAXBContextProperties.OXM_METADATA_SOURCE, "forum19384491/oxm.xml");
properties.put(JAXBContextProperties.MEDIA_TYPE, "application/json");
properties.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false);
properties.put(JAXBContextProperties.JSON_ATTRIBUTE_PREFIX, "@");
JAXBContext jsonJC = JAXBContext.newInstance(new Class[] {Zoo.class}, properties);
Marshaller marshaller = jsonJC.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(zoo, System.out);
}
}
Saída
Abaixo está a saída da execução do código de demonstração.
{
"animals" : [ {
"@type" : "tiger",
"name" : "Richard",
"furry" : true
}, {
"@type" : "elephant",
"name" : "Otis",
"furry" : false
}, {
"@type" : "tiger",
"name" : "Kirk",
"furry" : true
} ]
}