package cn.qg.qaplatform.utils;

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

import java.util.Map;

/**
 * json转换工具类
 */
public class JsonTransUtils {

    /**
     * json转换成对象
     * @param jsonStr
     * @return
     * @throws JsonProcessingException
     */
    public static Object jsonToObj(String jsonStr) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        Object obj = new Object();
        return obj = objectMapper.readValue(jsonStr, obj.getClass());
    }

    /**
     * 对象转换成json
     *
     * @param:传入对象
     * @return:json字符串
     */
    public static String objToJson(Object obj) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(obj);
    }

    /**
     * 字符串转换成map
     */
    public static Map<String, Object> strToMap(String str) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.readValue(str, Map.class);
    }

    /**
     * map转json对象
     */
    public static String mapToJson(Map<String, Object> map) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonStr = objectMapper.writeValueAsString(map);
        return jsonStr;
    }
}
