よく使われるJsonUtilツールクラス


よく使われるJsonUtilツールクラス

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.terminus.common.exception.ServiceException;
import java.util.List;

public class JsonUtils {

    //   jackson  
    private static ObjectMapper objectMapper;

    static {
        objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
      	objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
    }

    /**
     *       json   。
     */
    public static String objectToJson(Object data) {
        try {
            String string = objectMapper.writeValueAsString(data);
            return string;
        } catch (Exception e) {
           throw new ServiceException();
        }
    }
    
    /**
    * Json    
    */
	public static  T from(String json, TypeReference typeReference) {
        try {
            return objectMapper.readValue(json, typeReference);
        } catch (Exception e) {
            throw new ServiceException();
        }
    }
    
    /**
     *  json        
     */
    public static  T jsonToPojo(String jsonData, Class beanType) {
        try {
            T t = objectMapper.readValue(jsonData, beanType);
            return t;
        } catch (Exception e) {
           throw new ServiceException();
        }
    }

    /**
     *  json     pojo  list
     */
    public static  List jsonToList(String jsonData, Class beanType) {
        JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, beanType);
        try {
            List list = objectMapper.readValue(jsonData, javaType);
            return list;
        } catch (Exception e) {
           throw new ServiceException();
        }
     }
}     

json逆シーケンス化の使い方:
public User Mock(){
	return sonUtil.from(json,new TypeReference() { });
}

or

public List Mock(){
	return sonUtil.from(json,new TypeReference>() { });
}