zoukankan      html  css  js  c++  java
  • Json工具类

    import java.io.IOException;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.List;
    
    import com.fasterxml.jackson.annotation.JsonInclude.Include;
    import com.fasterxml.jackson.core.JsonProcessingException;
    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;
    
    
    public class JsonMapper {
    
        private static final ObjectMapper jsonMapper;
        
        static {
        	jsonMapper = new ObjectMapper();
        	DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        	jsonMapper.setDateFormat(df);
        	jsonMapper.setSerializationInclusion(Include.NON_NULL);
        	jsonMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        }
        
        public static String bean2Json(Object value){
        	try {
    			return jsonMapper.writeValueAsString(value);
    		} catch (JsonProcessingException e) {
    			throw new RuntimeException(e);
    		}
        }
        
        public static <T> T json2Bean(String json,Class<T> clazz){
        	try {
    			return jsonMapper.readValue(json, clazz);
    		} catch (IOException e) {
    			throw new RuntimeException(e);
    		}
        }
        
        public static <T> T json2Array(String json,TypeReference<?> type){
        	try {
    			return jsonMapper.readValue(json, type);
    		} catch (IOException e) {
    			throw new RuntimeException(e);
    		}
        }
    
    	public static <T> List<T> json2List(String json, Class<T> clazz){
    		try {
    			JavaType type = jsonMapper.getTypeFactory().constructParametrizedType(List.class,List.class,clazz);
    			return jsonMapper.readValue(json, type);
    		} catch (IOException e) {
    			throw new RuntimeException(e);
    		}
    	}
    }
    

      

  • 相关阅读:
    异常处理 try catch throw(C++)
    Kubernetes轻量级日志收集系统LokiStack
    第一章.java
    第四章.选择结构(二)
    java语法
    第三章if选择结构
    第二章.数据类型变量名和运算符
    【转载】跳槽七诫
    【转载】修改shell终端提示信息
    ubuntu11.10面板上输入法图标消失解决办法
  • 原文地址:https://www.cnblogs.com/piaxiaohui/p/9227066.html
Copyright © 2011-2022 走看看