package com.persagy.cameractl.utils;

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

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

public class JsonTools {
	private static ObjectMapper mapper = new ObjectMapper();
	
	public static String obj2Str(Object obj) throws JsonProcessingException {
		return null != obj ? mapper.writeValueAsString(obj) : null;
	}
	
	public static Map<String, Object> str2Map(String str) throws Exception {
		if(null == str) {
			return null;
		}
		
		return mapper.readValue(str, new TypeReference<Map<String, Object>>(){});
	}
	
	public static JsonNode str2JsonNode(String str) throws IOException {
		if(null != str) {
			return mapper.readTree(str);
		}
		return null;
	}
	
	public static <T> T jsonStr2Obj(String jsonStr, Class<T> clz) throws Exception {
		if(null == jsonStr) {
			return null;
		}
		
		return mapper.readValue(jsonStr, clz);
	}
	
	public static JsonNode newInstance() throws IOException {
		return mapper.readTree("{}");
	}
}
