fastjson 的简单使用,对象与JSON字符串互转

使用 fastjson 当然先要导入 JAR 包,下面是 maven 依赖的地址

<dependency>
    <groupId>com.alibabagroupId>
    <artifactId>fastjsonartifactId>
    <version>1.2.73version>
dependency>

先准备一个 Use 和 Grade 类

  • User.java
package top.shijialeya.po;

public class User {
    private String name;
    private Integer age;

    public User() {
    }

    public User(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

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

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
  • Grade.java
package top.shijialeya.po;

import java.util.ArrayList;
import java.util.List;

public class Grade {
    private String name;
    private List<User> users = new ArrayList<User>();

    public Grade() {
    }

    public Grade(String name, List<User> users) {
        this.name = name;
        this.users = users;
    }

    public String getName() {
        return name;
    }

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

    public List<User> getUsers() {
        return users;
    }

    public void setUsers(List<User> users) {
        this.users = users;
    }

    @Override
    public String toString() {
        return "Grade{" +
                "name='" + name + '\'' +
                ", users=" + users +
                '}';
    }
}

序列化

把 JavaBean 对象转成 JSON 格式的字符串

将对象转为 JOSN 字符主要使用到 JSON.toJSONString(Object)

  1. 简单的 Java 类转为 JSON
@Test
public void test01() {
    //简单 java 类转换成 JSON
    User user = new User("张三", 18);
    String userJSONString = JSON.toJSONString(user);
    System.out.println(userJSONString);
}

结果:

{"age":18,"name":"张三"}
  1. List 转 JSON 字符串,并且使用单引号
        @Test
        public void test02() {
            //List 转 JSON 字符串,使用单引号
            User u1 = new User("张三", 18);
            User u2 = new User("李四", 19);
            User u3 = new User("王五", 20);
            List<User> us = new ArrayList<>();
            us.add(u1);
            us.add(u2);
            us.add(u3);
            //SerializerFeature.UseSingleQuotes 使用单引号
            String usJSONString = JSON.toJSONString(us, SerializerFeature.UseSingleQuotes);
            System.out.println(usJSONString);
        }
     
      

    结果:

    [{'age':18,'name':'张三'},{'age':19,'name':'李四'},{'age':20,'name':'王五'}]
    
    1. Map 转 json,并且使用 JSON 格式化
    @Test
    public void test03() {
        //Map 转 json,JSON 格式化
        User u1 = new User("张三", 18);
        User u2 = new User("李四", 19);
        HashMap<String, User> map = new HashMap<>();
        map.put("key01", u1);
        map.put("key02", u2);
        //SerializerFeature.PrettyFormat JSON 格式化
        String mapJSONString = JSON.toJSONString(map, SerializerFeature.PrettyFormat);
        System.out.println(mapJSONString);
    }
    

    结果:

    {
    	"key02":{
    		"age":19,
    		"name":"李四"
    	},
    	"key01":{
    		"age":18,
    		"name":"张三"
    	}
    }
    
    1. 复杂 Java 类转 JSON 字符串,输出 Null 字段并且序列化写入类型信息
        @Test
        public void test04() {
            //复杂 Java 类转 JSON 字符串,输出 Null 字段。
            User u1 = new User("张三", 18);
            User u2 = new User(null, 19);
            List<User> us = new ArrayList<>();
            us.add(u1);
            us.add(u2);
            Grade grade = new Grade("华软", us);
            //缺省情况下 FastJSON 不输入为值 Null 的字段,可以使用 SerializerFeature.WriteMapNullValue 使其输出。
            //SerializerFeature.WriteClassName 序列化写入类型信息
            String gradeJSONString = JSON.toJSONString(grade, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteClassName);
            System.out.println(gradeJSONString);
        }
    

    结果:

    {"@type":"top.shijialeya.po.Grade","name":"华软","users":[{"age":18,"name":"张三"},{"age":19,"name":null}]}
    
    1. 对日期类进行个格式化
    @Test
    public void test05() {
        //对日期类进行个格式化
        String dateJSONString = JSON.toJSONString(new Date(), SerializerFeature.WriteDateUseDateFormat);
        System.out.println(dateJSONString);
    
        //指定输出的日期格式
        String dataJSON = JSON.toJSONStringWithDateFormat(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
        System.out.println(dataJSON);
    }
    

    结果:

    "2020-11-18 17:16:04"
    "2020-11-18 17:16:04.951"
    

    反序列化

    将 JSON 字符转换为 Java 对象

    1. json 转简单的 Java 对象
    @Test
    public void test01() {
        //json 转简单的 Java 对象
        String json = "{'age':18,'name':'张三'}";
        User user = JSON.parseObject(json, User.class);
        System.out.println(user);
    }
    

    结果:

    User{name='张三', age=18}
    
    1. json 转 List 数组
    @Test
    public void test02() {
        //json 转 List 数组
        String arrJson = "[{'age':18,'name':'张三'},{'age':19,'name':'李四'}]";
        List<User> userList = JSON.parseArray(arrJson, User.class);
        System.out.println(userList);
    }
    

    结果:

    [User{name='张三', age=18}, User{name='李四', age=19}]
    
    1. json 转复杂类型的 Java 对象
    @Test
    public void test03() {
        //json 转复杂类型的 Java 对象
        String jsonObject = "{'name':'华软','users':[{'age':18,'name':'张三'},{'age':19,'name':'李四'}]}";
        Grade grade = JSON.parseObject(jsonObject, Grade.class);
        System.out.println(grade);
    }
    

    结果:

    Grade{name='华软', users=[User{name='张三', age=18}, User{name='李四', age=19}]}
    
    1. json 转 List
    @Test
    public void test04() {
        //json 转 List
        String json = "[{'name':'华软','site':'太平'},{'name':'软件','users':'广从南路'}]";
        List<Map> mapList = JSON.parseArray(json, Map.class);
        for (Map map : mapList) {
            Set set = map.keySet();
            for (Object o : set) {
                System.out.println(o + " -> " + map.get(o));
            }
        }
    }
    

    结果:

    site -> 太平
    name -> 华软
    name -> 软件
    users -> 广从南路
    
    1. json 转 泛型 ( Map )
    @Test
    public void test05() {
        //json 转 泛型 ( Map> )
        String json = "{'hr':[{'age':18,'name':'张三'},{'age':19,'name':'李四'}],'rj':[{'age':20,'name':'王五'},{'age':21,'name':'赵六'}]}";
        Map<String, List<User>> map = JSON.parseObject(json, new TypeReference<Map<String, List<User>>>() {
        });
        Set<String> keys = map.keySet();
        for (String key : keys) {
            List<User> users = map.get(key);
            System.out.println(key + " -> " + users);
        }
    }
    

    结果:

    rj -> [User{name='王五', age=20}, User{name='赵六', age=21}]
    hr -> [User{name='张三', age=18}, User{name='李四', age=19}]
    
    1. 复杂的 json 转 Java 对象

    在主方法的目录下创建一个 query.json 文件,内容如下:

    [
      {
        "name": "华软",
        "users": [
          {
            "age": 18,
            "name": "张三"
          },
          {
            "age": 19,
            "name": "李四"
          }
        ]
      },
      {
        "name": "软件",
        "users": [
          {
            "age": 20,
            "name": "王五"
          },
          {
            "age": 21,
            "name": "赵六"
          }
        ]
      }
    ]
    

    对该 JSON 文件进行转换

    @Test
    //复杂的 json 转 Java 对象
    public void testTwo() throws IOException {
        //读取 query.json 文件的 json 数据
        ClassLoader cl = this.getClass().getClassLoader();
        InputStream inputStream = cl.getResourceAsStream("query.json");
        //需要导入 commons-io 包
        String jsonString = IOUtils.toString(inputStream, "utf-8");
        //先把外成转成数组
        List<Grade> grades = JSON.parseArray(jsonString, Grade.class);
        System.out.println(grades);
    }
    

    运行结果:

    [Grade{name='华软', users=[User{name='张三', age=18}, User{name='李四', age=19}]}, Grade{name='软件', users=[User{name='王五', age=20}, User{name='赵六', age=21}]}]
    

    commons-io 包坐标

    
    <dependency>
        <groupId>commons-iogroupId>
        <artifactId>commons-ioartifactId>
        <version>2.4version>
    dependency>
    

    你可能感兴趣的:(json,java)