欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringBoot 使用jackjson入门

程序员文章站 2022-06-01 08:31:11
...

SpringBoot中如果需要实现json的序列化和反序列化,我们会使用json解析工具。一般用到的有fastjson、GSON、Jackson
根据网上的测试,Jackson性能好一些,而且Jackson是SpringBoot默认引用的
本文记录SpringBoot如何使用Jackson

准备

1、在项目中创建包Jackson
2、分别创建4各类文件
2.1、Company实体类(里面包含Department的list)
2.2、Department实体类
2.3、jsonController controller类,接收测试请求
2.4、JsonHelper Jackson操作类
如题所示
SpringBoot 使用jackjson入门

每个类内容如下
Company


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

public class Company {

    private  String name;
    private  String address;
    private  int employeesCount;
    private List<Department> departmentArrayList;


    public String getName() {
        return name;
    }

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

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public int getEmployeesCount() {
        return employeesCount;
    }

    public void setEmployeesCount(int employeesCount) {
        this.employeesCount = employeesCount;
    }

    public List<Department> getDepartmentArrayList() {
        return departmentArrayList;
    }

    public void setDepartmentArrayList(List<Department> departmentArrayList) {
        this.departmentArrayList = departmentArrayList;
    }
}

Department


public class Department {

    private  String name;
    private  int employeesCount;

    public String getName() {
        return name;
    }

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

    public int getEmployeesCount() {
        return employeesCount;
    }

    public void setEmployeesCount(int employeesCount) {
        this.employeesCount = employeesCount;
    }
}

jsonController


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@RequestMapping("/json")
public class jsonController {

    private  final Logger logger = LoggerFactory.getLogger(this.getClass());//对象方式初始化Log对象

    @GetMapping("")
    public String index() throws Exception {
        JsonHelper jm = new JsonHelper();

        //1、对象<->Json
            //准备数据
        Company c = getCompany();
            //对象转Json
        String json =  jm.toJson(c);
        logger.info("1.1、对象转Json="+json);
            //Json转对象
        Company obj = jm.fromJson(json,Company.class);
        logger.info("1.2、Json转对象="+ obj.getDepartmentArrayList().get(0).getName());

        //2、Map<->Json
            //Json转Map
        Map map = jm.fromJson(json,Map.class);
        List<Map> tempList =  (List<Map>)map.get("departmentArrayList");
        logger.info("2.1、Json转Map="+tempList.get(0).get("name"));

            //Map转Json
        json =  jm.toJson(map);
        logger.info("2.2、Map转Json="+json);

        //3、List<Object> <->Json
            //准备数据
        List<Company> companyList = new ArrayList<Company>();
        companyList.add(getCompany());
        companyList.add(getCompany());
        companyList.add(getCompany());

            //List<Object>转Json
        json =  jm.toJson(companyList);
        logger.info("3.1、List<Object>转Json="+json);

            //Json转List<Object>
        List<Company> companyListDecode = jm.fromJson(json,new TypeReference<List<Company>>() {});
        logger.info("3.2、Json转List<Object>="+companyListDecode.get(0).getDepartmentArrayList().get(0).getName());

        //4、Map<String, Object><-> Json
            //准备数据
        Map<String, Company> map1 = new HashMap<String, Company>() ;
        map1.put("1",getCompany());
        map1.put("2",getCompany());
        map1.put("3",getCompany());

            //Map<String, Object>转Json
        json =  jm.toJson(map1);
        logger.info("4.1、Map<String, Object>转Json="+json);

            //Json转Map<String, Object>
        Map<String, Company> map1Decode = jm.fromJson(json,new TypeReference<Map<String, Company>>() {});
        logger.info("4.2、Json转Map<String, Object>="+map1Decode.get("1").getDepartmentArrayList().get(0).getName());

        //5、List<Map<String, Object>><->Json
            //准备数据
        List<Map<String, Company>> listMap =new ArrayList<Map<String, Company>>();
        Map<String, Company> map2 = new HashMap<String, Company>() ;
        map2.put("a",getCompany());
        map2.put("b",getCompany());
        map2.put("c",getCompany());
        listMap.add(map1);
        listMap.add(map2);

            //List<Map<String, Object>> 转Json
        json =  jm.toJson(listMap);
        logger.info("5.1、List<Map<String, Object>> 转Json="+json);

            //Json 转 List<Map<String, Object>>
        List<Map<String, Company>> listMapDecode = jm.fromJson(json,new TypeReference<List<Map<String, Company>>>() {});
        logger.info("5.2、List<Map<String, Object>> 转Json="+listMapDecode.get(0).get("1").getDepartmentArrayList().get(0).getName());

        return "";
    }


    private  Company getCompany()
    {
        long time = new Date().getTime();
        String sTime =  String.valueOf(time);
        Company c = new Company();
        c.setEmployeesCount(10);
        c.setName("公司名"+sTime);

        List list = new ArrayList();
        Department d1= new Department();
        d1.setEmployeesCount(5);
        d1.setName("部门1"+sTime);

        Department d2= new Department();
        d2.setEmployeesCount(5);
        d2.setName("部门2"+sTime);

        list.add(d1);
        list.add(d2);

        c.setDepartmentArrayList(list);

        return  c;
    }
}

JsonHelper


import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.util.JSONPObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class JsonHelper {


    private  Logger logger = LoggerFactory.getLogger(this.getClass());
    ObjectMapper mapper;

    public  JsonHelper()
    {
        mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    public  JsonHelper(JsonInclude.Include include)
    {
        mapper = new ObjectMapper();
        mapper.setSerializationInclusion(include);
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }


    public  String toJson(Object object) throws JsonProcessingException {
        return mapper.writeValueAsString(object);
    }

    public  <T> T fromJson(String json, Class<T> cls) throws IOException {
        return mapper.readValue(json, cls);
    }

    public  <T> T fromJson(String json,TypeReference valueTypeRef) throws IOException {
        return mapper.readValue(json, valueTypeRef);
    }
}

转换方式

共举例如下几种转换方式(整体在jsonController文件中,这里分别拆出来说明)

对象<->Json

//1、对象<->Json
        //准备数据
        Company c = getCompany();
        //对象转Json
        String json =  jm.toJson(c);
        logger.info("1.1、对象转Json="+json);
        //Json转对象
        Company obj = jm.fromJson(json,Company.class);
        logger.info("1.2、Json转对象="+ obj.getDepartmentArrayList().get(0).getName());

Map<->Json

//2、Map<->Json
            //Json转Map
        Map map = jm.fromJson(json,Map.class);
        List<Map> tempList =  (List<Map>)map.get("departmentArrayList");
        logger.info("2.1、Json转Map="+tempList.get(0).get("name"));

            //Map转Json
        json =  jm.toJson(map);
        logger.info("2.2、Map转Json="+json);

List<Object> <->Json

//3、List<Object> <->Json
            //准备数据
        List<Company> companyList = new ArrayList<Company>();
        companyList.add(getCompany());
        companyList.add(getCompany());
        companyList.add(getCompany());

            //List<Object>转Json
        json =  jm.toJson(companyList);
        logger.info("3.1、List<Object>转Json="+json);

            //Json转List<Object>
        List<Company> companyListDecode = jm.fromJson(json,new TypeReference<List<Company>>() {});
        logger.info("3.2、Json转List<Object>="+companyListDecode.get(0).getDepartmentArrayList().get(0).getName());

Map<String, Object><-> Json

//4Map<String, Object><-> Json
            //准备数据
        Map<String, Company> map1 = new HashMap<String, Company>() ;
        map1.put("1",getCompany());
        map1.put("2",getCompany());
        map1.put("3",getCompany());

            //Map<String, Object>转Json
        json =  jm.toJson(map1);
        logger.info("4.1、Map<String, Object>转Json="+json);

            //Json转Map<String, Object>
        Map<String, Company> map1Decode = jm.fromJson(json,new TypeReference<Map<String, Company>>() {});
        logger.info("4.2、Json转Map<String, Object>="+map1Decode.get("1").getDepartmentArrayList().get(0).getName());

List<Map<String, Object>><->Json

//5List<Map<String, Object>><->Json
            //准备数据
        List<Map<String, Company>> listMap =new ArrayList<Map<String, Company>>();
        Map<String, Company> map2 = new HashMap<String, Company>() ;
        map2.put("a",getCompany());
        map2.put("b",getCompany());
        map2.put("c",getCompany());
        listMap.add(map1);
        listMap.add(map2);

            //List<Map<String, Object>> 转Json
        json =  jm.toJson(listMap);
        logger.info("5.1、List<Map<String, Object>> 转Json="+json);

            //Json 转 List<Map<String, Object>>
        List<Map<String, Company>> listMapDecode = jm.fromJson(json,new TypeReference<List<Map<String, Company>>>() {});
        logger.info("5.2、List<Map<String, Object>> 转Json="+listMapDecode.get(0).get("1").getDepartmentArrayList().get(0).getName());

测试

访问controller的方法,查看日志可以看出来每种转换都可以成功转为json,也可以成功转为对象

其它特性

在有些时候,我们会希望进行一些特殊处理,例如json不

忽略字段

@JsonIgnore 进行JSON操作时忽略该属性。
对于实体类中,如果有某个字段不希望参与json序列化与反序列化,可以把属性标记为@JsonIgnore
例如Company这个类
如果我们给Name、Address、employeesCount三个属性赋值了,序列化出来的内容是

{
    "name": "公司名1504688970821", 
    "address": "地址", 
    "employeesCount": 10
}

如果employeesCount是一个内容计数的值,不希望参与序列化,我们可以标记它

    @JsonIgnore
    private  int employeesCount;

这样再次序列化的结果就变为了

{
    "name": "公司名1504689048950", 
    "address": "地址"
}

处理时间类型

@JsonFormat(pattern = “yyyy年MM月dd日”) 时间格式化
我们在Company实体类增加一个Date类型的属性,并且赋值序列化


    private Date createDate;

    public Date getCreateDate() {
        return createDate;
    }

    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }

赋值然后再序列化,得到的内容是

{
    "name": "公司名1504689283756", 
    "address": "地址", 
    "createDate": 1504689283756
}

可以看到时间是一个数字
我们标记这个属性,再次序列化

{
    "name": "公司名1504689362487", 
    "address": "地址", 
    "createDate": "2017年09月06日"
}

时间按照指定的格式显示了

更改字段序列化名

@JsonProperty(“newName”) 改字段名
默认情况下,字段名是什么,序列化出来的key值也就是什么,如果我们希望序列化出来的名字和字段名不一样,则需要使用这个标记
我们把Company的name标记为newName

    @JsonProperty("newName")
    private  String name;

然后进行序列化

{
    "address": "地址", 
    "createDate": "2017年09月06日", 
    "newName": "公司名1504689496978"
}

可以看出来,结果出来的key就使用了自定义的名字

相关标签: springboot jackson