您的位置:首页 > Web前端 > JavaScript

fastjson用法3

2015-07-23 17:24 916 查看
JSON类设置格式的方法

public class JSONDemo02 {
public static void main(String[] args) {

Student student = new Student(1, "张三", 15, new Date());
Course course=new Course(1,"语文");
Score score=new Score(student,course,90.50);

//SerializerFeature是一个枚举类型,定义了20多种JSON格式
/**
* SerializerFeature:
* WriteDateUseDateFormat——日期格式化
* DisableCircularReferenceDetect——禁止循环引用检测
* UseSingleQuotes——字符串使用单引号包含
* UseISO8601DateFormat——使用ISO8601格式输出日期
* SortField——属性排序,,默认为true 按照属性的字母排序
* PrettyFormat——格式化输出
* WriteClassName——JSON中包含全类名
* BrowserCompatible——序列化中文为Unicode码,使浏览器兼容
* WriteNonStringKeyAsString——把所有key值按照字符串形式输出
* QuoteFieldNames——输出key时是否使用双引号,默认为true
* WriteMapNullValue——是否输出值为null的字段,默认为false
* WriteNullNumberAsZero——数值字段如果为null,输出为0,而非null
* WriteNullListAsEmpty——List字段如果为null,输出为[],而非null
* WriteNullStringAsEmpty——字符类型字段如果为null,输出为”“,而非null
* WriteNullBooleanAsFalse——Boolean字段如果为null,输出为false,而非null
* SkipTransientField——不序列化Transient标示的属性,默认为true
* (上述属性没有全部测试,可能会有错误)
* ... ...
*/

//JSON类的toJSONString方法中有一个变长参数,参数类型为SerializerFeature
String jsonString=JSON.toJSONString(score,SerializerFeature.WriteDateUseDateFormat);
System.out.println(jsonString);
//输出结果:
//{"course":{"courseId":1,"courseName":"语文"},"score":90.5,"student":{"age":15,"birth":"2015-07-23 16:20:56","name":"张三","studentId":1}}

List<Course> list=new ArrayList<>();
list.add(course);
list.add(course);

//默认格式
String jsonString2=JSON.toJSONString(list);
System.out.println(jsonString2);
//输出结果:
//[{"courseId":1,"courseName":"语文"},{"$ref":"$[0]"}]

//禁止循环引用检测
String jsonString3=JSON.toJSONString(list,SerializerFeature.DisableCircularReferenceDetect);
System.out.println(jsonString3);
//输出结果:
//[{"courseId":1,"courseName":"语文"},{"courseId":1,"courseName":"语文"}]

/**
* 循环引用语法
* {"$ref":"$"} 引用根对象
* {"$ref":"@"} 引用自己
* {"$ref":".."} 引用父对象
* {"$ref":"../.."} 引用父对象的父对象
* {"$ref":"$.members[0].reportTo"} 基于路径的引用
* https://github.com/alibaba/fastjson/wiki/%E5%BE%AA%E7%8E%AF%E5%BC%95%E7%94%A8#%E8%AF%AD%E6%B3%95 */

//writeJSONStringTo方法直接输出JSON,可以当做工具方法使用
//需要的参数有:
//1.需要转化为JSON的对象(Object类型对象),2.PrintWriter,3.变长参数SerializerFeature
//使用单引号,日期格式化
PrintWriter out=new PrintWriter(System.out);
JSON.writeJSONStringTo(score, out, SerializerFeature.UseSingleQuotes,SerializerFeature.WriteDateUseDateFormat);
//输出结果
//{'course':{'courseId':1,'courseName':'语文'},'score':90.5,'student':{'age':15,'birth':'2015-07-23 16:37:34','name':'张三','studentId':1}}

//设置全局输出格式的方式
//单个SerializerFeature
//如果使用=赋值会覆盖默认的4种格式
JSON.DEFAULT_GENERATE_FEATURE |=SerializerFeature.WriteDateUseDateFormat.getMask();

System.out.println(JSON.toJSONString(score));
//数组形式
JSON.DEFAULT_GENERATE_FEATURE |=SerializerFeature.of(new SerializerFeature[]{SerializerFeature.WriteDateUseDateFormat,SerializerFeature.UseSingleQuotes});
System.out.println(JSON.toJSONString(score));

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  JSON fastjson java