• JSON操作


    一、JSON形式

    JSON键/值对由键和值组成,键必须是字符串,值可以是字符串(string)、数值(number) 、对象(object)、数组(array)、true、false、null。

    例子:

    {
        "name": "liuzijian",
        "age": 27,
        "hobby": ["basketball","running","swimming"],
        "istall": false,
        "isyoung": true,
        "money": null,
        "other": {
            "gender": "male",
            "city": "nanjing",
            "email": "liuzijian15@huawei.com"
        }
    }

     二、JAVA中Json的操作

    1、主要有四种jar包提供了json操作:

    • JSON官方
      <dependency>
          <groupId>org.json</groupId>
          <artifactId>json</artifactId>
          <version>20180813</version>
      </dependency>
    • GSON
      <dependency>
          <groupId>com.google.code.gson</groupId>
          <artifactId>gson</artifactId>
          <version>2.8.5</version>
      </dependency>
    • FastJSON
      <dependency>
          <groupId>com.alibaba</groupId>
          <artifactId>fastjson</artifactId>
          <version>1.2.54</version>
      </dependency>
    • jackson
      <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-core</artifactId>
          <version>2.9.8</version>
      </dependency>

    2、定义实体类

    Department类:

    import lombok.Data;
    
    @Data
    public class Department
    {
        private Integer departmentId;
    
        private String departmentName;
    
        public Department(Integer departmentId, String departmentName)
        {
            this.departmentId = departmentId;
            this.departmentName = departmentName;
        }
      //默认构造函数,由jackson解析json字符串为对象时调用
        public Department()
        {
    
        }
    }

    Employee类:

    import lombok.Data;
    
    import java.util.List;
    
    @Data
    public class Employee
    {
        private String name;
    
        private Integer id;
    
        private Integer age;
    
        private Double salary;
    
        private List<Department> departments;
    
        public Employee(String name, Integer id, Integer age, Double salary, List<Department> departments)
        {
            this.name = name;
            this.id = id;
            this.age = age;
            this.departments = departments;
        }
    
        public Employee()
        {
    
        }
    }

    3、JSON操作

       3.1定义JSON操作类

    import java.util.ArrayList;
    import java.util.List;
    
    public class JSONTest
    {
        private String json;private Employee employee;
    
        public void init()
        {
         json = "{"id":1,"name":"liuzijian","age":27,"salary":5000.1,"departments":[{"departmentId":1,"departmentName":"CBC"},{"departmentId":2,"departmentName":"SCB"}]}";
            Department department1 = new Department(1, "CBC");
            Department department2 = new Department(2, "SCB");
            List<Department> departments = new ArrayList<>();
            departments.add(department1);
            departments.add(department2);
            employee = new Employee("liuzijian", 1, 27, 5000.1, departments);
        }
    }

      下面开始在这个类中添加方法测试json操作。

       3.2 使用JSON官方包

      1)解析json字符串

        public void testJsonToObjectInJson()
        {
            org.json.JSONObject jsonObject = new org.json.JSONObject(json);
            Employee employee = new Employee();
            employee.setId(jsonObject.getInt("id"));
            employee.setName(jsonObject.getString("name"));
            employee.setAge(jsonObject.getInt("age"));
            employee.setSalary(jsonObject.getDouble("salary"));
    
            List<Department> departments = new ArrayList<>();
            org.json.JSONArray jsonArray = jsonObject.getJSONArray("departments");
            for (int i = 0;i < jsonArray.length();i++)
            {
                org.json.JSONObject item = jsonArray.getJSONObject(i);
                Department department = new Department(item.getInt("departmentId"), item.getString("departmentName"));
                departments.add(department);
            }
    
            employee.setDepartments(departments);
    
            System.out.println(employee);
        }

      2)使用官方包将对象解析为字符串比较麻烦

      3.3 使用fastjson包

      1)从json字符串中解析出对象

        public void testJsonToObjectInFastJson()
        {
            Employee employee = com.alibaba.fastjson.JSON.parseObject(json, Employee.class);
            System.out.println(employee);
        }

      2)将对象解析为json字符串

        public void testObjectToJsonInFastJson()
        {
            String json = com.alibaba.fastjson.JSON.toJSONString(employee);
            System.out.println(json);
        }

      3.4 使用gson包

      1)将对象解析为json字符串

        public void testObjectToJsonInGson()
        {
            com.google.gson.Gson gson = new com.google.gson.Gson();
            String json = gson.toJson(employee);
            System.out.println(employee);
        }

      2)从json字符串中解析出对象

        public void testJsonToObjectInGson()
        {
            com.google.gson.Gson gson = new com.google.gson.Gson();
            Employee employee = gson.fromJson(json, Employee.class);
            System.out.println(employee);
        }

      3.5 使用jackson包,SpringMVC内置的解析器就是这个

      1)从json字符串中解析出对象

        public void testJsonToObjectInJackson() throws Exception
        {
            com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
            Employee employee = mapper.readValue(json, Employee.class);
            System.out.println(employee);
        }

      2)将对象解析为json字符串

        public void testObjectToJsonInJackson() throws JsonProcessingException
        {
            com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
            String json = mapper.writeValueAsString(employee);
            System.out.println(json);
        }

    除了JSON官方的对类没有要求,剩下的都要求是标准的类,否则无法解析,因为都用到了反射。

  • 相关阅读:
    阻塞队列之LinkedTransferQueue
    BlockingQueue drainTo()
    jedis常用API
    在Redis集群中使用pipeline批量插入
    序列化
    springmvc单文件上传
    hibernateValidate
    springmvc使用spring自带日期类型验证
    springmvc自定义日期编辑器
    springmvc__SimpleUrlHandlerMapping(对访问地址进行加工,以键值对的形式)
  • 原文地址:https://www.cnblogs.com/langren1992/p/10176230.html
Copyright © 2020-2023  润新知