7

Here are my classes:

@XmlRootElement(name="Zoo")
class Zoo {
    //@XmlElementRef
    public Collection<? extends Animal> animals;
}

@XmlAccessorType(XmlAccessType.FIELD)
@XmlSeeAlso({Bird.class, Cat.class, Dog.class})
@XmlDiscriminatorNode("@type")
abstract class Animal {
    @XmlElement
    public String name; 
}

@XmlDiscriminatorValue("Bird")
@XmlRootElement(name="Bird")
class Bird extends Animal {
    @XmlElement
    public String wingSpan;
    @XmlElement
    public String preferredFood;
}

@XmlDiscriminatorValue("Cat")
@XmlRootElement(name="Cat")
class Cat extends Animal {
    @XmlElement
    public String favoriteToy;
}

@XmlDiscriminatorValue("Dog")
@XmlRootElement(name="Dog")
class Dog extends Animal {
    @XmlElement
    public String breed;
    @XmlElement
    public String leashColor;
}

Here is the serialized JSON:

   {
        "animals": [
            {
                "type": "Bird",
                "name": "bird-1",
                "wingSpan": "6 feets",
                "preferredFood": "food-1"
            },
            {
                "type": "Cat",
                "name": "cat-1",
                "favoriteToy": "toy-1"
            },
            {
                "type": "Dog",
                "name": "dog-1",
                "breed": "bread-1",
                "leashColor": "black"
            }
        ]
    }

Here is the de-serializer code:

public static <T> T Deserialize_Moxy(String jsonStr, Class<?>[] cl) throws JAXBException {
    InputStream is = new ByteArrayInputStream(jsonStr.getBytes());
    JAXBContext jc = JAXBContext.newInstance(cl);         
    Unmarshaller unmarshaller = jc.createUnmarshaller();

    // Marshal to JSON
    unmarshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
    unmarshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, false);
    @SuppressWarnings("unchecked")
    T obj = (T)unmarshaller.unmarshal(is);
    return obj;
}

Here is the exception:

Exception in thread "main" javax.xml.bind.UnmarshalException
 - with linked exception:
[Exception [EclipseLink-25008] (Eclipse Persistence Services - 2.4.1.v20121003-ad44345): org.eclipse.persistence.exceptions.XMLMarshalException
Exception Description: A descriptor with default root element  was not found in the project]
    at org.eclipse.persistence.jaxb.JAXBUnmarshaller.handleXMLMarshalException(JAXBUnmarshaller.java:1014)
    at org.eclipse.persistence.jaxb.JAXBUnmarshaller.unmarshal(JAXBUnmarshaller.java:147)
    at com.bp.samples.json.generics.Foo.Deserialize_Moxy(Foo.java:271)
    at com.bp.samples.json.generics.Foo.main(Foo.java:111)
Caused by: Exception [EclipseLink-25008] (Eclipse Persistence Services - 2.4.1.v20121003-ad44345): org.eclipse.persistence.exceptions.XMLMarshalException
Exception Description: A descriptor with default root element  was not found in the project
    at org.eclipse.persistence.exceptions.XMLMarshalException.noDescriptorWithMatchingRootElement(XMLMarshalException.java:143)
    at org.eclipse.persistence.internal.oxm.record.SAXUnmarshallerHandler.startElement(SAXUnmarshallerHandler.java:222)
    at org.eclipse.persistence.internal.oxm.record.json.JSONReader.parseRoot(JSONReader.java:161)
    at org.eclipse.persistence.internal.oxm.record.json.JSONReader.parse(JSONReader.java:118)
    at org.eclipse.persistence.internal.oxm.record.SAXUnmarshaller.unmarshal(SAXUnmarshaller.java:827)
    at org.eclipse.persistence.internal.oxm.record.SAXUnmarshaller.unmarshal(SAXUnmarshaller.java:350)
    at org.eclipse.persistence.internal.oxm.record.SAXUnmarshaller.unmarshal(SAXUnmarshaller.java:334)
    at org.eclipse.persistence.oxm.XMLUnmarshaller.unmarshal(XMLUnmarshaller.java:407)
    at org.eclipse.persistence.jaxb.JAXBUnmarshaller.unmarshal(JAXBUnmarshaller.java:133)
    ... 2 more

Also a question on the serialized JSON: Is there a way to get the JSON serializer to publish "@type" instead of "type". Currently, it looks like the objects having the property "type". If we could decorate it with "@", it will be more obvious that this is more of a type info than a property.

Thanks, Behzad

Behzad Pirvali
  • 764
  • 3
  • 10
  • 28

1 Answers1

20

Below are my answers to your two questions:

Question #1 - Exception

When you use the MarshallerProperties.JSON_INCLUDE_ROOT property to turn off root elements then you need to use one of the unmarshal methods that takes a Class parameter to tell MOXy the type of object you wish to unmarshal.

StreamSource json = new StreamSource("src/forum14246033/input.json");
Zoo zoo = unmarshaller.unmarshal(json, Zoo.class).getValue();

Question #2

Also a question on the serialized JSON: Is there a way to get the JSON serializer to publish "@type" instead of "type". Currently, it looks like the objects having the property "type". If we could decorate it with "@", it will be more obvious that this is more of a type info than a property.

The @ prefix indicates that a field/property maps to an XML attribute. You can use the JAXBContextProperties.JSON_ATTRIBUTE_PREFIX property to specify a prefix to qualify data that was mapped to an XML attribute.

properties.put(JAXBContextProperties.JSON_ATTRIBUTE_PREFIX, "@");

FULL EXAMPLE

Demo

package forum14246033;

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>(2);
        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/forum14246033/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" : "Bird",
      "name" : "bird-1",
      "wingSpan" : "6 feets",
      "preferredFood" : "food-1"
   }, {
      "@type" : "Cat",
      "name" : "cat-1",
      "favoriteToy" : "toy-1"
   }, {
      "@type" : "Dog",
      "name" : "dog-1",
      "breed" : "bread-1",
      "leashColor" : "black"
   } ]
}

DOMAIN MODEL

I don't recommend using public fields in your domain model, but if you go that way you can reduce your metadata down to the following:

Zoo

import java.util.Collection;

class Zoo {
    public Collection<? extends Animal> animals;
}

Animal

import javax.xml.bind.annotation.XmlSeeAlso;
import org.eclipse.persistence.oxm.annotations.XmlDiscriminatorNode;

@XmlSeeAlso({Bird.class, Cat.class, Dog.class})
@XmlDiscriminatorNode("@type")
abstract class Animal {

    public String name; 

}

Bird

import org.eclipse.persistence.oxm.annotations.XmlDiscriminatorValue;

@XmlDiscriminatorValue("Bird")
class Bird extends Animal {
    public String wingSpan;
    public String preferredFood;
}

jaxb.properties

To specify MOXy as your JAXB (JSR-222) provider you need to include a file called jaxb.properties in the same package as your domain model with the following entry:

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
bdoughan
  • 147,609
  • 23
  • 300
  • 400
  • Thank u so much. That modification made the de-serializer to work. On question #2, I know that, so maybe '@' is not the best indicator since as you said it shows the xml attribute. The reason for suggestion is that on the JACKSON side, I have seen that meta-data is injected using '@' (like @class com....). That being said, don't you agree that it would be better to somehow decorate 'type' like '#type' to indicate that this is not an object property. Thank U SO MUCH – Behzad Pirvali Jan 10 '13 at 02:23
  • Actually the reason for recommending '@' sign was that based on my understanding JSON parsers know about it. So, ideally 'type' should be decorated with something like this: "@xsi:type". This makes it also clear that type is not an xml attribute. – Behzad Pirvali Jan 10 '13 at 02:34
  • @BehzadPirvali - I have definitely seen people qualifying nodes like the inheritance indicator. This answer actually factors in the `@` prefix. I have updated my answer to include the JSON document. – bdoughan Jan 10 '13 at 11:18
  • Sorry, but I am not sure I understand your last sentence. What do you mean with "including a JSON document"? – Behzad Pirvali Jan 11 '13 at 07:41
  • @BehzadPirvali - I just meant that I updated my answer to include the JSON document that is produced/consumed by the demo code that I posted originally. – bdoughan Jan 11 '13 at 11:32
  • Boughan, Oh, OK, Thank U. Back to my question, I feel that it would be good if MOXy could be enhanced to distinguish between "type" being a "type-info" and "xml attributes" as well as "xml elements". Ideally a "type-info", like "type" in this case, could be prefixed with "@xsi:", while "xml-attributes" are prefixed with "@"? – Behzad Pirvali Jan 12 '13 at 16:36
  • Is it possible to eliminate from the output this piece `{ "animals" : ` and the `}` at the end? so in this way to unwrap the list? – Coder Jun 06 '13 at 14:00
  • @Sergio - Yes you can just marshal/unmarshal the collection of animals directly. If you start a new questions I will post an example as an answer. – bdoughan Jun 06 '13 at 15:01