jackson 操作 List 与 String 互转

直接看实例:

package com.elq.product.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.elq.product.dao.LogsDao;
import com.elq.product.entity.LogsEntity;
import com.elq.product.service.IndexService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service("IndexService")
public class IndexServiceImpl extends ServiceImpl<LogsDao, LogsEntity> implements IndexService {
    
    

    public final static ObjectMapper mapper = new ObjectMapper();

    @Override
    public List<LogsEntity> getIndexList() {
    
    
        //数据库获取数据
        List<LogsEntity> logsEntities = this.baseMapper.selectList(null);

        //******************list对象转字符串***************************
        String s ="";
        try {
    
    
            s = mapper.writeValueAsString(logsEntities);
        } catch (JsonProcessingException e) {
    
    
            e.printStackTrace();
        }

        //********************json转list对象**********************
        JavaType javaType = getCollectionType(ArrayList.class, LogsEntity.class);
        List<LogsEntity> configList=new ArrayList<>();
        try {
    
    
            configList =  mapper.readValue(s, javaType);//这里不需要强制转换
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }

        return logsEntities;
    }
    /**
     * 获取泛型的Collection Type
     * @param collectionClass 泛型的Collection
     * @param elementClasses 元素类
     * @return JavaType Java类型
     * @since 1.0
     */
    public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
    
    
        return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
    }

}

猜你喜欢

转载自blog.csdn.net/YL3126/article/details/120883625