7

ここに私のクラスがあります:

@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;
}

シリアル化された 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"
            }
        ]
    }

デシリアライザーのコードは次のとおりです。

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;
}

例外は次のとおりです。

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

また、シリアル化された JSON に関する質問: JSON シリアライザーに「type」ではなく「@type」を公開させる方法はありますか。現在、プロパティ「type」を持つオブジェクトのように見えます。「@」で装飾できれば、これがプロパティというよりも型情報であることがより明白になります。

ありがとう、ベザド

4

1 に答える 1

19

以下は、2 つの質問に対する私の回答です。

質問 1 - 例外

プロパティを使用MarshallerProperties.JSON_INCLUDE_ROOTしてルート要素をオフにする場合は、アンマーシャリングするオブジェクトのタイプを MOXy に通知unmarshalするパラメータを受け取るメソッドの 1 つを使用する必要があります。Class

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

質問2

また、シリアル化された JSON に関する質問: JSON シリアライザーに「type」ではなく「@type」を公開させる方法はありますか。現在、プロパティ「type」を持つオブジェクトのように見えます。「@」で装飾できれば、これがプロパティというよりも型情報であることがより明白になります。

プレフィックスは、@フィールド/プロパティが XML 属性にマップされることを示します。プロパティを使用しJAXBContextProperties.JSON_ATTRIBUTE_PREFIXて、XML 属性にマップされたデータを修飾するプレフィックスを指定できます。

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

完全な例

デモ

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/出力

{
   "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"
   } ]
}

ドメインモデル

ドメイン モデルでパブリック フィールドを使用することはお勧めしませんが、そのようにすれば、メタデータを次のように減らすことができます。

動物園

import java.util.Collection;

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

動物

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; 

}

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

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

jaxb.properties

MOXy を JAXB (JSR-222) プロバイダーとして指定するにはjaxb.properties、次のエントリを使用して、ドメイン モデルと同じパッケージで呼び出されるファイルを含める必要があります。

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
于 2013-01-09T21:05:49.987 に答える