package com.ffii.core.utils;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

/**
 * JSON Utils
 *
 * @author Patrick
 */
public abstract class JsonUtils {

	// Default mapper instance
	private static final ObjectMapper mapper = new ObjectMapper();
	
	/**
	 * Method that can be used to serialize any Java value as a JSON String.
	 */
	public static String toJsonString(Object obj) {
		try {
			mapper.registerModule(new JavaTimeModule());
			mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
			return mapper.writeValueAsString(obj);
		} catch (JsonProcessingException e) {
			return null;
		}
	}

	/**
	 * Read from JSON String.
	 *
	 * @param content
	 *            JSON String content
	 * @param valueType
	 *            the return type
	 */
	public static <T> T fromJsonString(String content, Class<T> valueType) throws JsonParseException, JsonMappingException, IOException {
		return mapper.readValue(content, valueType);
	}

}