将对象或集合转成JSON数据

需要的jar包

        <!--jackson -->
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.11.1</version>
		</dependency>

 工具类

package com.wc.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.text.SimpleDateFormat;

public class JsonUtil {

    private static ObjectMapper mapper = new ObjectMapper();

    public static String getJson(Object o){
        return getJson(o,"yyyy-HH-dd HH:mm:ss");
    }

    public static String getJson(Object o ,String time){
        //关闭时间戳解析功能
        mapper.configure(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS,false);
        SimpleDateFormat simpleFormatter = new SimpleDateFormat(time);
        mapper.setDateFormat(simpleFormatter);
        try {
            //最后将转换好的json对象发送出去
            return mapper.writeValueAsString(o);
        }catch (JsonProcessingException e){
            e.printStackTrace();
        }
        return null;

    }


}
    原文作者:ip36900044
    原文地址: https://blog.csdn.net/ip36900044/article/details/122606541
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞