虽然使用FastJSON来生成JSON数据很是简单java
最经常使用的的方法就是JSON.toJSONString()静态方法,这个方法参数能够给一个String,也能够是一个int,也能够给一个Object类型(包括集合数组),也能够是一个JavaBean 等等,说明其存在多个重载方法spring
Admin admin2=adminService.findByName(admin.getAdminName()); String json = JSON.toJSONString(admin2); ServletActionContext.getResponse().setContentType("application/json;charset=utf-8"); ServletActionContext.getResponse().getWriter().write(json); return NONE;
可是我在实际使用过程当中仍是发现了一些值得注意的地方,好比说:以前写过的JQuery解析FastJSON生成的JSON数据会出现的错误数据库
今天我要记录下一些注意点json
方法一:数组
在JavaBean对象对应字段前加注解,这样生成的json也不包含该字段app
@JSONField(serialize=false) private String userName;
方法二:ide
在须要生成JSON的时候使用fastjson的过滤器测试
PropertyFilter profilter = new PropertyFilter(){ @Override public boolean apply(Object object, String name, Object value) { if(name.equalsIgnoreCase("age")){ //false表示age字段将被排除在外 return false; } return true; } }; json = JSON.toJSONString(user, profilter); System.out.println(json);
我我的推荐使用第二种,虽然代码多了些,可是若是出现该字段有须要不进行过滤的状况,就不太灵活了spa
再将数据库中的日期时间生成JSON的时候,可能会出现以毫秒或者是格式不一致的问题,应该如何指定使用的日期时间格式?就要使用@JSONField注解中的format属性了code
仍是在JavaBean的日期时间字段使用注解
//经过注解对日期转化为JSON进行格式化 @JSONField (format="yyyy-MM-dd HH:mm:ss") private Date date;
fastJSON也能够将JSON解析为所对应的JavaBean,使用的是JSON类的parseObject静态方法。
我在src下放入一段JSON数据:
{
"userName":"lz",
"password":"321",
"birthday":"2017-07-29 13:50:22",
"jineng":[
"Struts2","springMVC"
]
}
并写好对应的JavaBean,在JavaBean中jineng属性使用的List集合
测试的方法:
@Test public void fun4() throws Exception{ String path = MyTest.class.getResource("/test.json").getFile(); File file=new File(path); String json = FileUtils.readFileToString(file); User user=JSON.parseObject(json, User.class); System.out.println(user.getJineng()); System.out.println(user.getJineng().getClass()); }
输出结果:
[Struts2, springMVC]
class java.util.ArrayList
最终fastJSON将数据封装到JavaBean中,同时也完成了对集合属性的具体化