简体   繁体   English

Spring MVC-具有@ResponseBody批注的XML响应(Spring + XML)

[英]Spring MVC - XML response with @ResponseBody annotation (Spring + XML)

I need to send xml reponse from my application to incoming HTTP request. 我需要将XML响应从我的应用程序发送到传入的HTTP请求。 For this i reffered THIS LINK . 为此,我推荐了此链接 This example returns the xml 本示例返回xml

<coffee>
   <name>arabica</name>
   <quantity>10<quantity>
</coffee>

But i need response like 但是我需要像

<coffee>arabica</coffee> 

Here there is no specific root element. 这里没有特定的根元素。 please suggest how to i get this response by modifying java object. 请建议我如何通过修改Java对象来获得此响应。

Early response will be really helpful 尽早做出反应将非常有帮助

i Modified the code as below but i am not getting output expected 我修改了代码如下,但我没有得到预期的输出

@XmlRootElement(name = "coffee")
public class Coffee
{
  String coffee;

  public String getCoffee()
  {
   return coffee;
  }

  @XmlElement
  public void setCoffee(String coffee)
  {
    this.coffee = coffee;
  }
}

For this code i am getting output like below 对于此代码,我将得到如下输出

<coffee><coffee>arabica</coffee></coffee>

This is impossible. 这是不可能的。 A xml-node can either contain (1)a value or (2)other xml-nodes, a jackson class must contain other xml-nodes. 一个xml节点可以包含(1)个值,也可以包含(2)个其他xml节点,杰克逊类必须包含其他xml节点。

But you can return a string instead of a instance of Coffee . 但是您可以返回字符串而不是Coffee的实例。

Try to return a String directly. 尝试直接返回字符串。

return "<coffee>"+coffee+"</coffee>";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM