REST: convert XML content passed with POST to a ja

2019-08-09 17:41发布

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条回答
乱世女痞
2楼-- · 2019-08-09 18:21

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;

}
查看更多
登录 后发表回答