package com.emato.ich.utils;

import com.emato.ich.utils.Log;

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

import java.nio.charset.StandardCharsets;

/**
 * Jackson工具类
 */
public class JacksonUtils {

    public static final ObjectMapper objectmapper = new ObjectMapper();

    public static String toJson(Object obj) {
        try {
            return objectmapper.writeValueAsString(obj);
        } catch (JsonProcessingException jpe) {
            Log.d("JacksonUtils", "obj to json error");
            return null;
        } catch (Exception e) {
            return null;
        }
    }

    public static <T> T toObject(String jsonStr, Class<T> clazz) {
        try {
            return objectmapper.readValue(jsonStr.getBytes(StandardCharsets.UTF_8), clazz);
        } catch (JsonProcessingException jpe) {
            Log.d("JacksonUtils", "json to obj error");
            return null;
        } catch (Exception e) {
            return null;
        }
    }
}
