package com.ces;

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;

/***
 *   对象与JSON字符串转换工具类
 * @author Slet
 *
 */
public class ObjectMapperUtils {
    private static final ObjectMapper mapper=new ObjectMapper();
    /**
     * 对象-->JSON
     * @param data
     * @return
     */
    public static String toJSON(Object data) {
        String json=null;
        try {
            json=mapper.writeValueAsString(data);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return json;
    }
    /**
     * JSON-->对象
     * @param <T>
     * @param json
     * @param clazz
     * @return
     */
    public static <T>T toObject(String json,Class<T> clazz) {
        T t=null;
        try {
            t = mapper.readValue(json, clazz);
        } catch (JsonParseException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } catch (JsonMappingException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return t;
    }
}
