dropwizard中的xml响应格式

时间:2018-09-17 05:55:16

标签: java xml jersey dropwizard

我想要单个api的xml和json格式。 我的问题是在xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Fruits>
   <response>
     <name>Mango</name>
     <qty>2kg</qty>
     <rate>60.00</rate>
   </response>
   <response>
     <name>Banana</name>
     <qty>2kg</qty>
     <rate>80.00</rate>
   </response>
</Fruits>

我得到这样的回应,但我想要这样的回应

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<response>
<list>
  <item>
      <name>Mango</name>
      <qty>2kg</qty>
      <rate>60.00</rate>
  </item>
</list>
</response>

POJO是

@XmlRootElement(name ="response")
public class Fruit {    
private String name;
private String qty;
private String rate;
public GetSellerBuyerCode(String name, String qty, String rate) {
    this.name=name;
    this.qty=qty;
    this.rate=rate;     
}
@XmlElement
public String getName() {
    return name;
}
@XmlElement
public String getQty() {
    return qty;
}
@XmlElement
public String getRate() {
    return rate;
}   
}

控制器代码:

@Path("/Fruits")
@POST
@Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
public Response getSellersBySellerCodeDet() {
    List<Fruit> list = new ArrayList<Fruit>();      
    list = buyDAO.getFruits();
    return Response.ok(new GenericEntity<List<Fruit>>(list) {}).build();
}

我尝试了@XmlRootElement,但是类名作为根元素来了。谁能告诉我们如何避免这种情况。并且正在使用dropwizard 1.1.2和jersey 2.25.1

1 个答案:

答案 0 :(得分:0)

以下解决方案对我有用,未尝试使用dropwizard,仅尝试使用Jaxb。

可以请您检查吗?

@XmlRootElement(name="Response")
@XmlAccessorType(XmlAccessType.FIELD)
class FruitList{

@XMLElement(name="item")
private ArrayList<Fruit> list;

public ArrayList<Fruit> getList() {
return list;
}

public void setList(ArrayList<Fruit> list) {
this.list = list;
}

}


public class Fruit {  
@XmlElement(name="name")

private String name;
@XmlElement(name="qty")
private String qty;
@XmlElement(name="rate")
private String rate;

public Fruit () {

}

public Fruit (String name, String qty, String rate) {
    this.name=name;
    this.qty=qty;
    this.rate=rate;     
}
public String getName() {
    return name;
}

public String getQty() {
    return qty;
}

public String getRate() {
    return rate;
}   
}