2013-02-05 66 views
8

जैक्सन के माध्यम से एक xml विशेषता के रूप में जावा var (उदा। Int) को क्रमबद्ध करने का कोई तरीका है? मुझे इसका एहसास करने के लिए कोई भी शानदार जैक्सन या जेसन एनोटेशन (@XmlAttribute @ javax.xml.bind.annotation.XmlAttribute) नहीं मिल रहा है।जावा ऑब्जेक्ट को जैक्सन के साथ xml विशेषता के रूप में क्रमबद्ध कैसे करें?

उदा।

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> 

वहाँ एक रास्ता तत्वों के बजाय गुण प्राप्त करने के लिए है? मदद के लिए धन्यवाद!

+0

इंट प्रकार के साथ कोई समस्या नहीं है। मैंने कभी भी कोशिश की, मुझे विशेषताओं के बजाय एक्सएमएल तत्व मिल गए। – Divine

उत्तर

13

ठीक है मुझे एक समाधान मिला।

यह एक AnnotaionIntrospector रजिस्टर करने के लिए यदि आप जैक्सन-dataformat-एक्सएमएल

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

लापता टैग था

@JacksonXmlProperty (isAttribute = true)

तो बस परिवर्तन का उपयोग आवश्यक नहीं था गेटटर:

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

और यह ठीक काम करता है। बस इस का पालन करने के लिए कैसे:

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

@JacksonXmlProperty XML नामस्थान और एक संपत्ति के लिए स्थानीय नाम निर्दिष्ट अनुमति देता है; साथ ही साथ संपत्ति को XML तत्व या विशेषता के रूप में लिखा जाना है या नहीं।

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); 
+0

आपका कोड बहिष्कृत लगता है, लेकिन मैं इसे आज़माउंगा। – Divine