注: 私はEclipseLink JAXB (MOXy )のリーダーであり、JAXB (JSR-222)エキスパート グループのメンバーです。
すでに JAXB マッピングが確立されており、XML を JSON に変換しているため、同じ JAXB メタデータを使用してオブジェクトから XML へのマッピングとオブジェクトから JSON へのマッピングの両方を提供する EclipseLink JAXB (MOXy) に関心があるかもしれません。
お客様
以下は、JAXB アノテーションを含むサンプル モデルです。
package forum11599191;
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Customer {
@XmlAttribute
private int id;
private String firstName;
@XmlElement(nillable=true)
private String lastName;
private List<String> email;
}
jaxb.properties
MOXy を JAXB プロバイダーとして使用するにはjaxb.properties
、次のエントリを使用してドメイン モデルと同じパッケージに呼び出されるファイルを含める必要があります ( http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-asを参照)。 -your.html )。
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
入力.xml
<?xml version="1.0" encoding="UTF-8"?>
<customer id="123" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<firstName>Jane</firstName>
<lastName xsi:nil="true"/>
<email>jdoe@example.com</email>
</customer>
デモ
次のデモ コードは、XML からオブジェクトを取り込み、JSON を出力します。MOXy にはコンパイル時の依存関係がないことに注意してください。
package forum11599191;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Customer.class);
// Unmarshal from XML
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum11599191/input.xml");
Customer customer = (Customer) unmarshaller.unmarshal(xml);
// Marshal to JSON
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty("eclipselink.media-type", "application/json");
marshaller.marshal(customer, System.out);
}
}
JSON 出力
以下は、デモ コードを実行した結果の出力です。
{
"customer" : {
"id" : 123,
"firstName" : "Jane",
"lastName" : null,
"email" : [ "jdoe@example.com" ]
}
}
出力について注意すべき点がいくつかあります。
- フィールドは数値型であるため、
id
引用符なしで JSON にマーシャリングされました。
id
フィールドが にマッピングされていたとしても@XmlAttribute
、JSON メッセージにはこれに関する特別な指示はありません。
email
プロパティのList
サイズは 1 でした。これは JSON 出力で適切に表されます。
- この
xsi:nil
メカニズムは、lastName
フィールドにnull
値があることを指定するために使用されました。これは、JSON 出力で適切な null 表現に変換されています。
詳細については