fastjson 常用的方法

来源:互联网 发布:java 当月剩余天数 编辑:程序博客网 时间:2024/05/21 14:59

fastjson 是一个性能很好的 Java 语言实现的 JSON 解析器和生成器,来自阿里巴巴的工程师开发。

主要特点:

  • 快速FAST (比其它任何基于Java的解析器和生成器更快,包括jackson)

  • 强大(支持普通JDK类包括任意Java Bean Class、Collection、Map、Date或enum)

  • 零依赖(没有依赖其它任何类库除了JDK)


FastJSON是一个Java语言编写的高性能,功能完善,完全支持http://json.org的标准的JSON库

在使用之前必须下载这个包:fastjson-1.1.37.jar 或fastjson-1.1.39.jar (注意JDK的版本哦!)

一.序列化就是把JavaBean对象转成JSON格式的字符串

/** * 实体类 *  * @author Administrator *  */public class Student {private String name; // 用户名private int age; // 年龄        ............}

 具体的使用如下:
/** * (1)将实体对象转换成JSON对象  * String str_json = JSON.toJSONString(stu); */public static void entityToJSON() {// 对象Student stu = new Student("zhangsan", 20);// 将对象转换成JSON对象String str_json = JSON.toJSONString(stu);// 输出System.out.println("实体转化为Json" + str_json);}


/** * (2)将List对象转换成JSON对象          String json = JSON.toJSONString(list, true); */public static void listToJSON() {List<Student> list = new ArrayList<Student>();Student userinfo1 = new Student("mike", 25);Student userinfo2 = new Student("boy", 26);list.add(userinfo1);list.add(userinfo2);// true:是格式化样式String json = JSON.toJSONString(list, true);System.out.println("List集合转json格式字符串 :" + json);}

/** * (4)将复杂数据类型转换成JSON对象 * String jsonString = JSON.toJSONString(map,true); * */public static void MoreToJSON() {// map集合HashMap<String, Object> map = new HashMap<String, Object>();map.put("uname", "小飞");map.put("age", 21);map.put("sex", "F");// map集合HashMap<String, Object> temp = new HashMap<String, Object>();temp.put("name", "小明");temp.put("age", "23");// 将temp添加map集合中map.put("girlInfo", temp);// list集合List<String> list = new ArrayList<String>();list.add("aaa");list.add("bbb");list.add("ccc");// 将list添加map集合中map.put("hobby", list);String jsonString = JSON.toJSONString(map,true);System.out.println("复杂数据类型:" + jsonString);}


/** * (6)通过JSON将日期格式化 *  */public static void formatDate() {//日期 Date date= new Date(); String str = JSON.toJSONString(date); System.out.println("输出毫秒:"+str);  String dstr=JSON.toJSONString(date, SerializerFeature.WriteDateUseDateFormat); System.out.println("输出默认格式:"+dstr);  String zstr=JSON.toJSONStringWithDateFormat(date,"yyyy-MM-dd", SerializerFeature.WriteDateUseDateFormat); System.out.println("自定义格式:"+zstr);}



二.反序列化就是把JSON格式的字符串转化为Java Bean对象。


/** * (3)将字符数组转换成JSON对象  * JSONArray array = JSONArray.parseArray(string); */public static void StringArrayToJSON() {String string = "[['熊二',20],null,['翠花',21]]";JSONArray array = JSONArray.parseArray(string);System.out.println("数组:" + array);System.out.println("数组长度: " + array.size());}


/** * (5)将JSON对象转换成实体对象 * Student stu = JSON.parseObject(json, Student.class); */public static void JsonToEntity() {//jsonString json="{'name':'girl',age:20}";//  将JSON转换成实体对象Student stu = JSON.parseObject(json, Student.class);// 输出System.out.println("Json转化为实体:" + stu);}


总之:学习更多的方法的使用,查看API!!

0 0
原创粉丝点击