使用过程描述

引入包

  • 注意此Demo引入的版本是存在安全漏洞的,因此想要用到生产环境应使用最新版本
  1. <!-- fastjson依赖 -->
  2. <dependency>
  3. <groupId>com.alibaba</groupId>
  4. <artifactId>fastjson</artifactId>
  5. <version>1.2.15</version>
  6. </dependency>

对象声明

注意JSONField的声明是重要的,否则在Controller中识别不了。

  1. @Component
  2. public class UserDomain {
  3. @JSONField(serialize = false)
  4. private String userName;
  5. private String password;
  6. public String getUserName() {
  7. return userName;
  8. }
  9. public void setUserName(String userName) {
  10. this.userName = userName;
  11. }
  12. public String getPassword() {
  13. return password;
  14. }
  15. public void setPassword(String password) {
  16. this.password = password;
  17. }
  18. }

Controller中引用

需要在Idea中补足import引用,按提示处理就好。这里使用了依赖注入Autowire来注入个对象

  1. @RestController
  2. @RequestMapping("/")
  3. public class MRestController {
  4. @Autowired
  5. private UserDomain user;
  6. @RequestMapping("/info/{password}")
  7. public UserDomain info(@PathVariable String password){
  8. user.setUserName("111");
  9. user.setPassword(password);
  10. return user;
  11. }
  12. }

普通方式调用

  1. public class FastjsonTest {
  2. @Test
  3. public void jsonbean(){
  4. // JSON 字符串
  5. // String s = "{\"formId\":\"{$formId}\",\"link\":\"www.java3y.com\",\"text\":[{\"name\":\"java3y\",\"label\":\"3y\",\"value\":{\"value\":\"{$tureName}\",\"color\":\"\",\"emphasis\":\"\"}},{\"name\":\"java4y\",\"label\":\"3y\",\"value\":{\"value\":\"{$title}\",\"color\":\"\",\"emphasis\":\"\"}},{\"name\":\"java5y\",\"label\":\"5y\",\"value\":{\"value\":\"关注我的公众号,更多干货\",\"color\":\"#ff0040\",\"emphasis\":\"\"}}],\"yyyImg\":\"\",\"yyyAge\":\"\",\"pagepath\":\"\"}";
  6. DreamDo dreamDo = new DreamDo();
  7. dreamDo.setId(2L);
  8. dreamDo.setUrl("http://baidu.com");
  9. dreamDo.setLen(String.valueOf("http://baidu.com".length()));
  10. String s = JSON.toJSONString(dreamDo);
  11. System.out.println(s);
  12. DreamDo dreamDob = JSON.parseObject(s, DreamDo.class);
  13. System.out.println(dreamDob.getUrl());
  14. }
  15. }

预期运行效果:

注意:应该没有userId和phone,但是最简单的Demo即可运行。
【20180924】SpringBoot支持Fastjson(与RestApi) - 图1

问题排查

如果无法识别Controller

  1. @SpringBootApplication(scanBasePackages = "Controller") // 记得加scanBasePackages
  2. public class DemoApplication {
  3. public static void main(String[] args)
  4. {
  5. // ApplicationContext ctx = SpringApplication.run(DemoApplication.class, args);
  6. // String[] beanNames = ctx.getBeanDefinitionNames();
  7. // Arrays.sort(beanNames);
  8. // for (String beanName : beanNames)
  9. // {
  10. // System.out.println(beanName);
  11. // }
  12. SpringApplication.run(DemoApplication.class, args);
  13. }
  14. }