/*******************************************************************************
 * Copyright 2Fi Business Solutions Ltd.
 *
 * This code is part of the Core project.
 *
 * This code is copyrighted. Under no circumstances should any party, people,
 * or organization should redistribute any portions of this code in any form,
 * either verbatim or through electronic media, to any third parties, unless
 * under explicit written permission by 2Fi Business Solutions Ltd.
 ******************************************************************************/
package com.ffii.core.utils;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 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 {
			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);

	}

	public static Map<String, Object> fromJsonStringAsMap(String content)
			throws JsonParseException, JsonMappingException, IOException {
		return mapper.readValue(content, new TypeReference<Map<String, Object>>() {
		});
	}

	public static List<Map<String, Object>> fromJsonStringAsListOfMap(String content)
			throws JsonParseException, JsonMappingException, IOException {
		return mapper.readValue(content, new TypeReference<List<Map<String, Object>>>() {
		});
	}

}