使用过程描述
引入包
- 注意此Demo引入的版本是存在安全漏洞的,因此想要用到生产环境应使用最新版本
<!-- fastjson依赖 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.15</version>
</dependency>
对象声明
注意JSONField的声明是重要的,否则在Controller中识别不了。
@Component
public class UserDomain {
@JSONField(serialize = false)
private String userName;
private String password;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Controller中引用
需要在Idea中补足import引用,按提示处理就好。这里使用了依赖注入Autowire来注入个对象
@RestController
@RequestMapping("/")
public class MRestController {
@Autowired
private UserDomain user;
@RequestMapping("/info/{password}")
public UserDomain info(@PathVariable String password){
user.setUserName("111");
user.setPassword(password);
return user;
}
}
普通方式调用
public class FastjsonTest {
@Test
public void jsonbean(){
// JSON 字符串
// 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\":\"\"}";
DreamDo dreamDo = new DreamDo();
dreamDo.setId(2L);
dreamDo.setUrl("http://baidu.com");
dreamDo.setLen(String.valueOf("http://baidu.com".length()));
String s = JSON.toJSONString(dreamDo);
System.out.println(s);
DreamDo dreamDob = JSON.parseObject(s, DreamDo.class);
System.out.println(dreamDob.getUrl());
}
}
预期运行效果:
注意:应该没有userId和phone,但是最简单的Demo即可运行。
问题排查
如果无法识别Controller
@SpringBootApplication(scanBasePackages = "Controller") // 记得加scanBasePackages
public class DemoApplication {
public static void main(String[] args)
{
// ApplicationContext ctx = SpringApplication.run(DemoApplication.class, args);
// String[] beanNames = ctx.getBeanDefinitionNames();
// Arrays.sort(beanNames);
// for (String beanName : beanNames)
// {
// System.out.println(beanName);
// }
SpringApplication.run(DemoApplication.class, args);
}
}