概要:
响应json
1.加入json依赖
2.idea需要将jar导入到WEB-IN文件夹下。(规范做法导入到WEB-IN下自建的lib文件下)
3.在对应的方法上加入@RequestMapping("")
或者将@Controller改成@RestController(该类的所有请求方法都以json格式返回)。
4.
spring的json依赖:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.10.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.10.3</version>
</dependency>
例子:
-
-
controller类:
@Controller //@RestController //该类的所有请求方法都以json格式返回 @RequestMapping("/json") public class JsonControlller { @RequestMapping("/respond") @ResponseBody //将返回值作为文本进行返回,并不是返回视图名称。 public List<User> respondJson(){ User user = new User(1,"dt","123456",new Date()); List<User> list = new ArrayList<>(); list.add(user); System.out.println(user); return list; } }
-
-
User类:
public class User { private Integer id; private String naem; //@JacksonInject//javaBean以json格式返回的时候自动忽略。 private String password; @JsonFormat(pattern = "yyyy-MM-dd") //以xxx格式返回数据 //@DateTimeFormat(pattern = "yyyy-MM-dd") //不能json格式化返回 private Date birthday; public User() {} public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public User(Integer id, String naem, String password, Date birthday) { this.id = id; this.naem = naem; this.password = password; this.birthday = birthday; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getNaem() { return naem; } public void setNaem(String naem) { this.naem = naem; } @Override public String toString() { return "User{" + "id=" + id + ", naem='" + naem + '\'' + ", password='" + password + '\'' + ", birthday=" + birthday + '}'; } }
-
-