package com.tzy.common.json;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import org.teasoft.honey.osql.core.Logger;

/**
 * JSON解析处理
 *
 */
public class JSON {
    private static final ObjectMapper objectMapper = new ObjectMapper();
    private static final ObjectWriter objectWriter = objectMapper.writerWithDefaultPrettyPrinter();
    private static ObjectWriter objectIgnoreNullWriter;

    static {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectIgnoreNullWriter = objectMapper.writerWithDefaultPrettyPrinter();
    }
    public static String marshal(Object value) throws Exception {
        try {
            return objectWriter.writeValueAsString(value);
        } catch (Exception e) {
            throw new Exception(e);
        }
    }

    public static String marshalIgnoreNull(Object value) {
        try {
            return objectIgnoreNullWriter.writeValueAsString(value);
        } catch (Exception e) {
            Logger.error("json err",e);
        }
        return null;
    }

    public static <T> T unmarshal(String str, Class<T> valueType) throws Exception {
        try {
            return objectMapper.readValue(str, valueType);
        } catch (Exception e) {
            throw new Exception(e);
        }
    }

}
