package com.xs.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

import java.io.IOException;
import java.io.InputStream;

/**
 * Jackson Object Mapper
 */
public class JacksonUtils {
	private static final ObjectMapper objectMapper = new ObjectMapper();
	public static String writeValueAsString(Object value) {
		try {
			objectMapper.registerModule(new JavaTimeModule());
			return objectMapper.writeValueAsString(value);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			return "";
		}
	}

	public static <T> T readValue(String content, Class<T> valueType) {
		try {
			objectMapper.registerModule(new JavaTimeModule());
			return objectMapper.readValue(content, valueType);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static <T> T readValue(String content, TypeReference<T> valueTypeRef) {
		try {
			objectMapper.registerModule(new JavaTimeModule());
			return objectMapper.readValue(content, valueTypeRef);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static <T> T readValue(InputStream src, Class<T> valueType) {
		try {
			objectMapper.registerModule(new JavaTimeModule());
			return objectMapper.readValue(src, valueType);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static <T> T convertValue(Object fromValue, Class<T> toValueType) {
		objectMapper.registerModule(new JavaTimeModule());
		return objectMapper.convertValue(fromValue, toValueType);
	}
}
