springboot返回值支持JSON和XML
在springboot实现,即支持JSON数据返回格式,也能同时支持XML
在前端调用的时候添加
Accept:application/xml 或者Accept:application/json
返回对应的格式
添加依赖
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.47</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-xml</artifactId> <version>2.11.0.rc1</version> </dependency>
实体类user.java
package com.example.demo.model; import lombok.*; import org.hibernate.annotations.CreationTimestamp; import javax.persistence.*; import java.util.Date; @Entity @Table(name = "users") @Data @Builder @ToString(callSuper = true) @NoArgsConstructor @AllArgsConstructor public class Users { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; private String name; @Column(updatable = false) @CreationTimestamp private Date createTime; }
数据访问层接口 UsersRepository.java
package com.example.demo.repository; import com.example.demo.model.Users; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface UsersRepository extends JpaRepository<Users,Integer> { }
控制器 测试方法 usersAdd
@RequestMapping("/users/add") public Users usersAdd(@RequestParam String name) { Users user = Users.builder().name(name).build(); log.info("User {}", user); usersRepository.save(user); return user; }
启动项目
使用postman
测试url
http://127.0.0.1:8080/users/add
参数 name 为 aaa
当 header 的 Accept 为 application/xml
返回
<Users>
<id>449</id>
<name>aaa</name>
<createTime>2020-04-02T06:57:08.997+0000</createTime>
</Users>
当 header 的 Accept 为 application/json
返回
{
"id": 450,
"name": "aaa",
"createTime": "2020-04-02T07:00:19.027+0000"
}