springboot返回json和xml
2019-12-24 本文已影响0人
莫夏_b560
依赖!!!
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
1、在pojo层添加User类
//被@XMLRootElement注解的类User,被描述为一个顶层的XML element */
@XmlRootElement
public class User {
String userName;
String userAge;
String userAddress; public User(String userName, String userAge, String userAddress) { this.userName = userName; this.userAge = userAge; this.userAddress = userAddress;
}
/** * 该注解可以将被注解的(非静态)字段,或者被注解的get/set方法对应的字段映射为本地元素,也就是子元素。
*/
@XmlElement
public String getUserName() { return userName;
}
public void setUserName(String userName) { this.userName = userName;
}
@XmlElement
public String getUserAge() { return userAge;
}
public void setUserAge(String userAge) { this.userAge = userAge;
}
@XmlElement
public String getUserAddress() { return userAddress;
}
public void setUserAddress(String userAddress) { this.userAddress = userAddress;
}
}
2、controller层
@RestController
public class UserController {
//http://localhost:8080/json
@GetMapping(value = "/json",produces = MediaType.APPLICATION_JSON_VALUE)
public User index(){
User user = new User("echola", "22", "深圳");
return user;
}
//http://localhost:8080/xml
@GetMapping(value = "/xml",produces = MediaType.APPLICATION_XML_VALUE)
public User XML(){
User user = new User("echola", "22", "深圳");
return user;
}
}
启动项目成功后,输入http://localhost:8080/json,页面上的json字符串:
image输入http://localhost:8080/xml,页面上Xml格式:
image