前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >FastJson的使用

FastJson的使用

作者头像
bear_fish
发布2018-09-19 15:00:02
1.5K0
发布2018-09-19 15:00:02
举报

介绍

FastJson据说是目前为止最快的JSON库,好吧,他说是就是了。

FastJson 的Wiki在这里:https://github.com/alibaba/fastjson/wiki/

Quick_Start 在这里:https://github.com/alibaba/fastjson/wiki/Quit_Start_cn

FastJson的API非常简单:

代码语言:javascript
复制
String text = JSON.toJSONString(obj); //序列化
VO vo = JSON.parseObject("{...}", VO.class); //反序列化

上代码

接着,上菜,不,上代码: 这里需要注意一个核心思想:JSON中的键值对就是Java中的Map,JSON中的数组就是Java中的List

POJO对象

代码语言:javascript
复制
package com.owen.fastjson.bean;

/**
 * POJO对象
 * 
 * @author Owen
 */
public class UserInfo {

    private String name;

    private int age;

    /**
     * FastJSON要求:需要提供默认构造方法
     */
    public UserInfo() {}

    public UserInfo(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

}

测试类

代码语言:javascript
复制
package com.owen.fastjson.app;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.owen.fastjson.bean.UserInfo;

/**
 * 测试类
 * 
 * @author Owen
 */
public class Main {

    /**
     * 简单序列化
     */
    private static void simpleTest() {
        UserInfo userInfo = new UserInfo("owen", 24);
        String jsonStr = JSON.toJSONString(userInfo);
        System.out.println(jsonStr);
    }

    /**
     * 复杂序列化
     */
    public static void complexTest() {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("username", "owen");
        map.put("age", 25);
        map.put("sex", "男");

        Map<String, Object> temp = new HashMap<String, Object>();
        temp.put("name", "jack");
        temp.put("age", 18);
        map.put("girinfo", temp);

        List<String> list = new ArrayList<String>();
        list.add("爬山");
        list.add("电影");
        list.add("旅游");
        map.put("hobby", list);

        String jsonStr = JSON.toJSONString(map);
        System.out.println(jsonStr);
    }

    /**
     * 日期序列化
     */
    public static void DateTest() {
        Date date = new Date();
        // 默认输出
        System.out.println("时间戳=" + JSON.toJSONString(date));
        // 默认的日期格式
        System.out.println("当前日期=" + JSON.toJSONString(date, SerializerFeature.WriteDateUseDateFormat));
        // 使用指定的日期格式
        System.out.println("当前日期=" + JSON.toJSONStringWithDateFormat(date, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteDateUseDateFormat));
    }

    /**
     * 简单反序列化
     */
    public static void simpleDeserializeTest() {
        String userInfoJSONStr = "{\"name\":\"owen\", \"age\":24}";
        UserInfo userInfo = JSON.parseObject(userInfoJSONStr, UserInfo.class);
        System.out.println("name = " + userInfo.getName() + ", age = " + userInfo.getAge());
    }

    /**
     * 泛型反序列化
     */
    public static void genericTypeDeserializeTest() {
        String jsonStr = "{\"user\":{\"name\":\"owen\", \"age\":24}";
        Map<String, UserInfo> map = JSON.parseObject(jsonStr, new TypeReference<Map<String, UserInfo>>() {});
        System.out.println(map.get("user").getAge() + "\n");

        String jsonStr2 = "{\"user\":[{\"name\":\"owen\", \"age\":24}, {\"name\":\"jack\", \"age\":18}]";
        Map<String, List<UserInfo>> users = JSON.parseObject(jsonStr2, new TypeReference<Map<String, List<UserInfo>>>() {});
        for (UserInfo info : users.get("user")) {
            System.out.println("name=" + info.getName());
            System.out.println("age=" + info.getAge());
            System.out.println("------------------");
        }
    }

    /**
     * test
     */
    public static void main(String[] args) {
        genericTypeDeserializeTest();
    }

}

import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;  import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;  public class TestFastjson {  //fastjson序列化单个对象 与反序列化  @Test  public void test1() {  Employee e = new Employee("001", "张三", 23, new Date());  //序列化  String jsonStr = JSON.toJSONString(e);  System.out.println(jsonStr);  //反序列化  Employee emp = JSON.parseObject(jsonStr, Employee.class);  System.out.println(emp.getName());  }  //fastjson序列化list集合 与反序列化  @Test  public void test2() {  Employee e = new Employee("001", "张三", 23, new Date());  Employee e2 = new Employee("002", "李四", 29, new Date());  List<Employee> emps = new ArrayList<Employee>();  emps.add(e);  emps.add(e2);  //fastjson序列化list, 返回来的是一个json数组,由[]包含两个json  String jsonArryStr = JSON.toJSONString(emps);  System.out.println(jsonArryStr);  // //反序列化  //法一  // List<Employee> empList = JSON.parseObject(jsonArryStr, new TypeReference<List<Employee>>(){} );  //法二  List<Employee> empList = JSON.parseArray(jsonArryStr,Employee.class);  for (Employee employee : empList) {  System.out.println(employee.getName());  System.out.println(employee.getBirthDay());  }  }  //fastjson序列化复杂对象 与反序列化  @Test  public void test3() {  Employee e = new Employee("001", "张三", 23, new Date());  Employee e2 = new Employee("002", "李四", 29, new Date());  List<Employee> emps = new ArrayList<Employee>();  emps.add(e);  emps.add(e2);  Dept dept = new Dept("d001", "研发部", emps);  //序列化  String jsonStr = JSON.toJSONString(dept);  System.out.println(jsonStr);  //反序列化  Dept d = JSON.parseObject(jsonStr, Dept.class);  System.out.println(d.getName());  //json转map  //法一  Map<String, Object> map1 = JSON.parseObject(jsonStr);//返回JSONObject,JSONObject实现Map<String, Object>接口  //法二  // Map<String, Object> map1 = (Map<String, Object>)JSON.parse(jsonStr);  for (String key : map1.keySet()) {  System.out.println(key + ":" + map1.get(key));  }  }  //fastjson 的 JSONObject的使用  @Test  public void test4() {  Employee e = new Employee("001", "张三", 23, new Date());  //序列化  String jsonStr = JSON.toJSONString(e);  System.out.println(jsonStr);  //反序列化 (可以和test1比较)   JSONObject emp = JSON.parseObject(jsonStr, JSONObject.class);  System.out.println(emp);  System.out.println(emp.getString("name"));  //再放一个Employee不存在的字段  emp.put("salary", "8000");  System.out.println(emp.toJSONString());  System.out.println(emp.get("salary"));  }  //fastjson序列化字符串  @Test  public void test5(){  List<String> strs = new ArrayList<String>();  strs.add("hello");  strs.add("world");  strs.add("banana");  //序列化  String jsonStr = JSON.toJSONString(strs);  System.out.println(jsonStr);  //反序列化  List<String> strList = JSON.parseObject(jsonStr, new TypeReference<List<String>>(){} );  // List<String> strList = JSON.parseArray(jsonStr, String.class);//等同于上一句  for (String str : strList) {  System.out.println(str);  }  }  //fastjson过滤字段  @Test  public void test6() {  Employee e = new Employee("001", "张三", 23, new Date());  Employee e2 = new Employee("002", "李四", 29, new Date());  List<Employee> emps = new ArrayList<Employee>();  emps.add(e);  emps.add(e2);  //构造过滤器  SimplePropertyPreFilter filter = new SimplePropertyPreFilter(Employee.class, "id", "age");  String jsonStr =JSON.toJSONString(emps, filter);  System.out.println(jsonStr);  }  //fastjson 日期处理  @Test  public void test7(){  Date date = new Date();  String dateStr = JSON.toJSONString(date);  System.out.println(dateStr);  String dateStr2 = JSON.toJSONStringWithDateFormat(date, "yyyy-MM-dd HH:mm:ss");  System.out.println(dateStr2);  //序列化实体  Employee emp = new Employee("001", "张三", 23, new Date());  //法一  String empStr = JSON.toJSONStringWithDateFormat(emp, "yyyy-MM-dd HH:mm:ss");  System.out.println(empStr);  //法二  String empStr2 = JSON.toJSONString(emp, SerializerFeature.WriteDateUseDateFormat);  System.out.println(empStr2);  //法三  SerializeConfig config = new SerializeConfig();  config.put(Date.class, new SimpleDateFormatSerializer("yyyy年MM月dd日 HH时mm分ss秒"));  String empStr3 = JSON.toJSONString(emp, config);  System.out.println(empStr3);  }  //fastjson 去掉值的双引号 实现JSONAware接口  @Test  public void test8(){  //见同级目录的Function.java  }  //fastjson 注解形式  (别名命名, 过滤字段, 日期格式)  @Test  public void test9(){  Student stu = new Student("001", "张三", 23, new Date());  String jsonStr = JSON.toJSONString(stu);  System.out.println(jsonStr);  }  }

文/程序猴(简书作者) 原文链接:http://www.jianshu.com/p/a04c428963a2 著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016年09月30日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 介绍
  • 上代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档