package cn.keking.utils;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

/**
 * @author Hikaru
 * Created  on 2018/5/30.
 */
public class ObjectMapperUtil {

  private static class ObjectMapHolder {

    private static final ObjectMapper INSTANCE = new ObjectMapper();
    static{
//      INSTANCE.setSerializationInclusion(Include.NON_NULL);
    }
  }


  public static ObjectMapper getObjectInstance() {
    return ObjectMapHolder.INSTANCE;
  }

  /**
   * 将对象转换为json字符串
   */
  public static <T>  String obj2string(T t) {
    try {
      return getObjectInstance().writeValueAsString(t);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }


  /**
   * 将字符串转为对象
   */
  public static <T> T str2obj(String jsonStr, Class<T> cls) {
    try {
      return getObjectInstance().readValue(jsonStr, cls);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  public static<T> String obj2Str(T t){
    try {
      return getObjectInstance().writeValueAsString(t);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }




}
