JsonUtil工具类

使用了Jackson和fastjson两种。因为Jackson的json字符串转数组还不会弄。所以先用fastjson进行字符串转list

package util;

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;


public class JsonUtil {

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

        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);
    }
}
 

转载于:https://my.oschina.net/u/3358860/blog/3052426

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值