zoukankan      html  css  js  c++  java
  • jsonUtil

    package com.cinc.permissionservice.utils;
    
    
    import com.fasterxml.jackson.databind.JavaType;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import lombok.extern.slf4j.Slf4j;
    
    import java.io.IOException;
    import java.util.List;
    
    /**
     * @author
     */
    @Slf4j
    public class JsonUtil {
    	
    	public final static ObjectMapper OBJECT_MAPPER = new ObjectMapper();
    	/**
    	 * json字符串转化为对象
    	 * @param json
    	 * @return
    	 */
    	public static <T> T jsonStrToOject(String json,Class<T> clazz){
    		
    		T obj = null;
    		try {
    			obj = OBJECT_MAPPER.readValue(json, clazz);
    		} catch (IOException e) {
    
    			log.error("json转换错误",e);
    			throw new RuntimeException("请求对象转JSON失败,入参为非正常格式JSON对象");
    		}
    		return obj;
    	}
    	
    	/**
    	 * 对象转换为JSON
    	 * @param obj
    	 * @return
    	 */
    	public static String objectToJsonStr(Object obj){
    		
    		String jsonStr = null;
    		try {
    			jsonStr  = OBJECT_MAPPER.writeValueAsString(obj);
    		} catch (IOException e) {
    			log.error("json转换错误",e);
    			throw new RuntimeException("请求对象转JSON失败,入参为非正常格式JSON对象");
    		}
    		return jsonStr;
    	}
    	
    	public static <T> List<T> jsonToList(String json,Class<T> clazz){
    		try {
    			JavaType javaType = OBJECT_MAPPER.getTypeFactory().constructParametricType(List.class, clazz);
    			return OBJECT_MAPPER.readValue(json, javaType);
    		} catch (Exception e) {
    			log.error("json转换错误",e);
    			throw new RuntimeException("json转换失败");
    		} 
    	}
    	
    	
    }
    

      

  • 相关阅读:
    Struts学习之手动验证
    Struts学习之文件上传
    Struts学习之模型驱动
    Struts学习之类型转换
    Struts学习之自定义拦截器
    Java基础之"=="和 和 equals 方法的区别
    Hadoop学习之Hadoop案例分析
    Hadoop学习之Hadoop集群搭建
    Hadoop学习之自定义二次排序
    Hadoop学习之Mapreduce执行过程详解
  • 原文地址:https://www.cnblogs.com/HHR-SUN/p/11361791.html
Copyright © 2011-2022 走看看