JsonUtil工具類

使用了Jackson和fastjson兩種。由於Jackson的json字符串轉數組還不會弄。因此先用fastjson進行字符串轉listjava

package util;json

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;數組


import com.alibaba.fastjson.JSONArray;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;app


public class JsonUtil {this

    
    public enum LetterType {
        UPPERCASE(1),LOWERCASE(2);
        private final int type;.net

        private LetterType(int type) {
            this.type = type;
        }
        
        public int getType() {
            return type;
        }
    }
    
    /**
     * json字符串轉換javabean
     * @param json json字符串
     * @param bean 對象.class
     * @return T
     * @throws IOException 
     * @throws JsonMappingException 
     * @throws JsonParseException 
     * */
    @SuppressWarnings("unchecked")
    public static <T> T jsonStrToJava(String json,Class<?> bean) throws JsonParseException, JsonMappingException, IOException{
        if(json == null || json.equals("") ) {
            return null;
        }
        ObjectMapper objectMapper = new ObjectMapper();
        if(json.indexOf("/Date(")>=0) {
            json = JsonUtil.jsonDateToJavaDate(json);
        }
        return (T) objectMapper.readValue(json, bean);
    }
    
    /**
     * json字符串轉換list
     * @param json json字符串
     * @param bean 泛型類型如:Integer.class
     * @return T
     * @throws IOException 
     * @throws JsonMappingException 
     * @throws JsonParseException 
     * */
    @SuppressWarnings("unchecked")
    public static <T> List<T> jsonToJavaArr(String json,Class<?> bean) throws JsonParseException, JsonMappingException, IOException {
        if(json == null || json.equals("") ) {
            return null;
        }
        return (List<T>) JSONArray.parseArray(json, bean);
    }
    
    /**
     * json字符串轉換javabean
     * @param json json字符串
     * @param bean 對象.class
     * @param toggleCase 是否轉換key的大小寫。轉換爲全小寫或者全大寫
     * @param letterType 轉換枚舉類 UPPERCASE-大寫、LOWERCASE-小寫
     * @return T
     * @throws IOException 
     * @throws JsonMappingException 
     * @throws JsonParseException 
     * */
    @SuppressWarnings("unchecked")
    public static <T> T jsonStrToJava(String json,Class<?> bean,boolean toggleCase,LetterType letterType) throws JsonParseException, JsonMappingException, IOException{
        if(json == null || json.equals("") ) {
            return null;
        }
        ObjectMapper objectMapper = new ObjectMapper();
        if(toggleCase) {
            json =JsonUtil.convertLetter(json,letterType);
        }
        if(json.indexOf("/Date(")>=0) {
            json = JsonUtil.jsonDateToJavaDate(json);
        }
        return (T) objectMapper.readValue(json, bean);
    }
    
    /**
     * json字符串轉換key的大小寫
     * @param json json字符串
     * @param letterType 轉換枚舉類 UPPERCASE-大寫、LOWERCASE-小寫
     * @return json字符串
     * @throws IOException 
     * @throws JsonMappingException 
     * @throws JsonParseException 
     * */
    public static String convertLetter(String json,LetterType letterType) throws JsonParseException, JsonMappingException, IOException {
        if(json == null || json.equals("") ) {
            return null;
        }
        ObjectMapper objectMapper = new ObjectMapper();
        @SuppressWarnings("unchecked")
        Map<String,Object> map = objectMapper.readValue(json, Map.class);
        Map<String,Object> convertMap = new HashMap<String,Object>();
        System.out.println(map.size());
        for (Map.Entry<String, Object> entry : map.entrySet()) {
                if(letterType.getType()==1) {
                    convertMap.put(entry.getKey().toUpperCase(), entry.getValue());
                }else {
                    convertMap.put(entry.getKey().toLowerCase(), entry.getValue());
                }
        }
         return JsonUtil.javaToJson(convertMap);
    }
    
    /**
     *  javabean轉換json字符串
     * @return 
     * @throws JsonProcessingException 
     * */
    public static String javaToJson(Object bean) throws JsonProcessingException {
        if(bean == null ) {
            return null;
        }
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(bean);
        return json;
    }
    
    /**
     *  json字符串中存在Date(1558427619277+0800)相似的時間格式進行轉換
     *  @param    json json字符串
     * @return     json json字符串
     * @throws JsonProcessingException 
     * */
    public static String jsonDateToJavaDate(String json) throws JsonParseException, JsonMappingException, IOException {
        if(json == null || json.equals("") ) {
            return null;
        }
        ObjectMapper objectMapper = new ObjectMapper();
        @SuppressWarnings("unchecked")
        Map<String,Object> map = objectMapper.readValue(json, Map.class);
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            System.out.println(entry.getValue());
            if(entry.getValue()!=null && entry.getValue().toString().indexOf("/Date(")>=0) {
                String dateJSON = entry.getValue().toString().replace("/Date(","").replace(")/","");
                Long dateLong = Long.valueOf(dateJSON.substring(0, dateJSON.length()-5));
                Date date = new Date(dateLong);
                map.put(entry.getKey(), date);
            }
        }
        return JsonUtil.javaToJson(map);
    }
    
    /**   
     * 獲取泛型的Collection Type  
     * @param collectionClass 泛型的Collection   
     * @param elementClasses 實體bean   
     * @return JavaType Java類型     
     */  
    public static JavaType getCollectionType(ObjectMapper mapper,Class<?> collectionClass, Class<?>... elementClasses) {
            return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
        }
    
    public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
        //String json = "{\"AgreeDeliverGoodsTime\":null,\"AgreeTakerSingleTime\":null,\"BakCreateTime\":\"\\/Date(1558427619277+0800)\\/\"}";
        int[] a = new int[]{1,2,3,4};
        String aJson = JsonUtil.javaToJson(a);
        System.out.println(aJson);
        List<Integer> jsonArr = jsonToJavaArr(aJson, Integer.class);
        System.out.println(jsonArr);
        //Map<String, Object> jsonJava = JsonUtil.jsonStrToJava(json, Map.class, true, LetterType.LOWERCASE);
        //System.out.println(jsonJava);
    }
}
 orm

相關文章
相關標籤/搜索