Hi,
>> Another question: is it possible to do the same (sub-class) with
>> JSON? Maybe with jettison notation?
I'd also like to get de-serialization of JSON objects
with inheritance working, but haven't figured out how to do it yet,
at least with the default JSON notation. For example:
@GET
@Path("/animals/")
public AnimalList getAnimals(){
AnimalList al = new AnimalList();
al.addAnimal(new Dog("Fifi"));
al.addAnimal(new Cat("Daisy"));
return al;
}
@PUT
@Path("/animals/")
public Animal addAnimal(Animal a){
return a;
}
.. where:
@XmlRootElement(name="animalList")
public class AnimalList{
private List<Animal> animals = new ArrayList<Animal>();
..
}
@XmlRootElement(name="animal")
public class Animal {
private String name;
..
}
@XmlRootElement(name="cat")
public class Cat extends Animal {
..
}
@XmlRootElement(name="dog")
public class Dog extends Animal {
..
}
Cat and Dog classes need to be set up in the JAXB context, like
Paul wrote.
With XML everything works OK, e.g:
GET animals
->
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<animalList>
<animals xmlns:xsi="
http://www.w3.org/2001/XMLSchema-instance"
xsi:type="dog"
><name>Fifi</name>
</animals>
<animals xmlns:xsi="
http://www.w3.org/2001/XMLSchema-instance"
xsi:type="cat">
<name>Daisy</name>
</animals>
</animalList>
PUT animals
<animal xmlns:xsi="
http://www.w3.org/2001/XMLSchema-instance"
xsi:type="cat"><name>Daisy</name></animal>
->
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<cat><name>Daisy</name></cat>
(PUT "<cat><name>Daisy</name></cat>" works as well).
.. but with JSON (default notation) de-serializing subresources
isn't possible, as far as I've experimented:
GET test/animals
-> {"animalList":{"animals":[{"@type":"dog","name":"Fifi"},
{"@type":"cat","name":"Daisy"}]}}
PUT test/animals
{"animal":{"@type":"dog","name":"Fifi"}}
->
{"animal":{"name":"Fifi"}}
.. or:
PUT test/animals
{"dog":{"@type":"dog","name":"Fifi"}}
->
{"animal":{"name":"Fifi"}}
Default JSON notation doesn't support property namespaces, so the
"xsi:type" property isn't passed to JAXB and the object
is deserialized as an instance of the superclass. Not sure
why the root element doesn't translate to the correct subclass
in this example, but even if it did, it wouldn't help in the
cases, where the subclass is not the root element but a
subproperty.
Another example can be found in jersey issue 113:
https://jersey.dev.java.net/issues/show_bug.cgi?id=113
Could passing the xsi:type from JSON to JAXB in de-serialization
be possible with the other JSON notations?
Thanks,
Janne