REST: convert XML content passed with POST to a java object, attribute inside the element

霸气de小男生 提交于 2019-12-11 07:51:26

问题


I am working with REST services and i want to pass an XML-text with a POST request. My server is implemented in JAVA. Let's say that i am sending this XML:

<range>
  <higher value="3"></higher>
  <lower value="2"></lower>
</range>

As i understand (correct me if i am wrong), the easiest way to convert the XML in the request to a java object, is to define a class with the proper annotations. For example:

@XmlRootElement(name = "range")
public class RangeClass {

    @XmlElement (name = "lower")
    private int lower;

    @XmlElement (name = "higher")
    private int higher;

    .
    .
    ???
}

And then read it like this:

@POST
@PATH(<somePath>)
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.TEXT_PLAIN)
public String myFun(RangeClass range) {
  .
  .
  .
}

The thing that i am missing (if the other parts are correct) is how to define that i have attributes inside the elements. If i put an '@XmlAttribute' annotation this will refer to an attribute of the root element ('range') and not an attribute of a specific element ('lower' or 'higher').


回答1:


First and the easiest way is to create a Java mapping per each XML tag:

@XmlRootElement(name = "range")
public class RangeClass {

    private Higher higher;

    private Lower lower;
}

@XmlElement(name = "higher")
public class Higher {

    @XmlAttribute
    private int value;
}

@XmlElement(name = "lower")
public class Lower {

    @XmlAttribute
    private int value;
}

Second option is to change XML structure to:

<range>
  <higher>3</higher>
  <lower>2</lower>
</range>

Then you can use @XmlElement annotation:

@XmlRootElement(name = "range")
@XmlAccessorType(XmlAccessType.FIELD) 
public class RangeClass {

    @XmlElement
    private int lower;

    @XmlElement
    private int higher;

}

Third option is to use Eclipse Link Moxy and its @XmlPath annotation:

@XmlRootElement(name = "range")
@XmlAccessorType(XmlAccessType.FIELD) 
public class RangeClass {

    @XmlPath("lower/@value")
    private int lower;

    @XmlPath("higher/@value")
    private int higher;

}


来源:https://stackoverflow.com/questions/27719036/rest-convert-xml-content-passed-with-post-to-a-java-object-attribute-inside-th

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!