编程语言
首页 > 编程语言> > Util:Java对象转换成Json字符串、Json数据转换对象List

Util:Java对象转换成Json字符串、Json数据转换对象List

作者:互联网

package com.web.util;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.List;
import java.util.Map;

public class JsonUtils {

    //定义Jackson对象
    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 将对象转换成json对象
     * <p>Title:pojoToJson</p>
     * <p>Description:</p>
     *
     * @param data
     * @return
     */
    public static String objectToJson(Object data){
        try {
            String string = MAPPER.writeValueAsString(data);
            return string;
        }catch (JsonProcessingException e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将json结果集转换为对象
     *
     * @param jsonData json数据
     * @param  beanType 对象中的object类型
     * @return
     */
    public static <T> T jsonToPoJjo(String jsonData,Class<T> beanType){
        try {
            T t = MAPPER.readValue(jsonData,beanType);
            return t;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将json数据转换成pojo对象list
     * <p>Title: jsonToList</p>
     * <p>Description: </p>
     *
     * @param jsonData
     * @param beanType
     * @return
     */
    public static <T> List<T> jsonToList(String jsonData,Class<T> beanType){
        JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class,beanType);
        try {
            List<T> list = MAPPER.readValue(jsonData,javaType);
            return list;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public static Map jsonToMap(String str){
        Map maps = (Map)JSON.parse(str);
        System.out.println("这是来用Json类解析JSON字符串的!");
        for (Object map:maps.entrySet()){
            System.out.println(((Map.Entry)map).getKey()+"       "+((Map.Entry)map).getValue());
        }
        return maps;
    }
}

标签:Map,return,List,jsonData,Json,static,beanType,import,Java
来源: https://blog.csdn.net/weixin_42594968/article/details/118881861