SpringBoot 返回自定义的xml

一般方法

SpringBoot 默认返回格式是json,现在项目中需要后台返回xml格式的数据,通常做法是加入依赖 jackson-dataformat-xml


      com.fasterxml.jackson.dataformat
      jackson-dataformat-xml

然后设置请求方法的返回类型为 "application/xml"

 @RequestMapping(value="/greeting",produces = "application/xml",method= RequestMethod.GET)
    public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
    	Long id = counter.incrementAndGet();
    	Greeting greeting = new Greeting(id,name);
        return greeting;
    }

得到结果,这样做虽然简单,但只能得到默认与类名及其属性名称相同的xml标签,如果想要改变xml的各节点名称及属性只能换另一种方法


    1
    World

返回自定义的xml

首先,删掉依赖包 jackson-dataformat-xml

使用xml注解给返回类打上标签,注解中设置对应的xml节点名称。

常用注解:

@XmlRootElement:表示映射到根目录标签元素
@XmlElement:表示映射到子元素
@XmlAttribute:表示映射到属性

import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlElement;

@XmlRootElement(name="root")
public class Greeting {
	
    private  long id;
    
    private  String name;
    
    public Greeting() {
		
	}

    public Greeting(long id,String name) {
        this.id = id;
        
        this.name =name;
    }
   
    public long getId() {
        return id;
    }

    
    @XmlElement(name="ID")
	public void setId(long id) {
		this.id = id;
	}

    public String getName() {
		return name;
	}

    @XmlElement(name="MyName")
    public void setName(String name) {
		this.name = name;
	}
	
    
}

Controller

@RestController
public class GreetingController {
    
    private final AtomicLong counter = new AtomicLong();

    @ApiOperation(value="测试json",notes="默认输入为World")
    @RequestMapping(value="/greeting",produces = "application/xml",method= RequestMethod.GET)
    public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
    	Long id = counter.incrementAndGet();
    	Greeting greeting = new Greeting(id,name);
        return greeting;
    }
}

返回结果


    1
    World

 

你可能感兴趣的:(SpringBoot 返回自定义的xml)