JsonUtils转换工具类

1、代码如下:

package com.asia.web.cache;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;

@Component
public class JsonUtils {

    private static final Logger logger  = LoggerFactory.getLogger(JsonUtils.class);

    private static ObjectMapper objectMapper ;
    static {
        objectMapper = new ObjectMapper();
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    }

    public static Object convertJson2Object(String json,Class cla){
        try {
            return objectMapper.readValue(json,cla);
        }catch (Exception e){
            logger.error("json2Object异常",e);
        }
        return null;
    }

    public static String convertObject2Json (Object object){
        try{
            return objectMapper.writeValueAsString(object);
        }catch (Exception e){
            logger.error("convertObject2Json转换异常",e);
        }
        return "";
    }
}

2、结果:

JsonUtils转换工具类_第1张图片

3、补充:JSONObject、JSONArray

JsonUtils转换工具类_第2张图片

你可能感兴趣的:(JsonUtils转换工具类)