但是我们有时候是需要返回json对象的。
Spring Boot封装了JSON解析包Jackson的功能,只需要直接返回一个实体即可实现json的格式。
如下:
新建实体Sex.java
package com.biologic.entity;
public class Sex {
private String sex;
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
在接口中返回实体,如下:
package com.biologic.api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.biologic.entity.Sex;
@Controller
@EnableAutoConfiguration
public class SampleController {
@RequestMapping("/")
@ResponseBody
Sex home() {
Sex sex=new Sex();
sex.setSex("1");
return sex;
}
public static void main(String[] args) throws Exception {
SpringApplication.run(SampleController.class, args);
}
} |