9

xml属性としてjacksonを介してjavavar(intなど)をシリアル化する方法はありますか?これを実現するための特別なjacksonまたはjsonアノテーション(@XmlAttribute @ javax.xml.bind.annotation.XmlAttribute)が見つかりません。

例えば

public class Point {

    private int x, y, z;

    public Point(final int x, final int y, final int z) {
        this.x = x;
        this.y = y;
        this.z = z;
    }

    @javax.xml.bind.annotation.XmlAttribute
    public int getX() {
        return x;
    }
    ...
}

私が欲しいもの:

<point x="100" y="100" z="100"/>

しかし、私が得たのは:

<point>
    <x>100</x>
    <y>100</y>
    <z>100</z>
</point>

要素の代わりに属性を取得する方法はありますか?手伝ってくれてありがとう!

4

2 に答える 2

15

さて、私は解決策を見つけました。

jackson-dataformat-xml を使用する場合、AnnotaionIntrospector を登録する必要はありませんでした。

File file = new File("PointTest.xml");
XmlMapper xmlMapper = new XmlMapper();
xmlMapper.writeValue(file, new Point(100, 100, 100));

行方不明の TAG は

@JacksonXmlProperty(isAttribute=true)

ゲッターを次のように変更するだけです。

@JacksonXmlProperty(isAttribute=true)
public int getX() {
    return x;
}

そしてそれはうまくいきます。次の方法に従ってください。

https://github.com/FasterXML/jackson-dataformat-xml

@JacksonXmlProperty を使用すると、プロパティの XML 名前空間とローカル名を指定できます。また、プロパティを XML 要素または属性として記述するかどうかも指定します。

于 2013-02-05T18:44:30.217 に答える
1

JaxbAnnotationIntrospectorを登録しましたか?

ObjectMapper mapper = new ObjectMapper();
AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
// make deserializer use JAXB annotations (only)
mapper.getDeserializationConfig().setAnnotationIntrospector(introspector);
// make serializer use JAXB annotations (only)
mapper.getSerializationConfig().setAnnotationIntrospector(introspector);
于 2013-02-05T17:18:21.427 に答える