java对象与json串的相互转换 将Bean中的Timestamp转换为json中的日期字符串

import java.util.Map;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.DefaultValueProcessor;
import net.sf.json.util.JSONUtils;

import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class BeanJsonConverterUtil {
    private static final Logger logger = LoggerFactory.getLogger(BeanJsonConverterUtil.class);

    /**
     * 将java对象转换成json串
     * @param obj
     * @return
     */
    @SuppressWarnings("rawtypes")
    public static String getJsonStrByObject(Object obj){
        JsonConfig jsonConfig = new JsonConfig();
        
        jsonConfig.registerDefaultValueProcessor(String.class,  
                new DefaultValueProcessor() {                      
                    public Object getDefaultValue(Class type) {  
                        return null;  
                    }                    
                });
        
        jsonConfig.registerDefaultValueProcessor(Integer.class,  
            new DefaultValueProcessor() {                      
                public Object getDefaultValue(Class type) {  
                    return null;  
                }                    
            });  
        jsonConfig.registerDefaultValueProcessor(Long.class,  
                new DefaultValueProcessor() {                      
                    public Object getDefaultValue(Class type) {  
                        return null;  
                    }                    
                }); 
        jsonConfig.registerDefaultValueProcessor(Character.class,  
                new DefaultValueProcessor() {                      
                    public Object getDefaultValue(Class type) {  
                        return null;  
                    }                    
                });  
        
        jsonConfig.registerJsonValueProcessor(java.sql.Timestamp.class,new JsonDateValueProcessor("yyyy-MM-dd HH:mm:ss")); 
            
        try{
            JSONObject jsonObj = JSONObject.fromObject(obj,jsonConfig);
            return jsonObj.toString();
        }catch (Exception e){
            logger.error("对象转换成json串失败!",e);
        }
        return null;
    }

    /**
     * 将json串转换成java对象(非嵌套对象)
     * @param jsonStr
     * @param cls
     * @return
     */
    @SuppressWarnings("rawtypes")
    public static Object getObjectByJsonStr(String jsonStr,Class cls){    
        String[] formats={"yyyy-MM-dd HH:mm:ss","yyyy-MM-dd"};          
        
        try
        {
            JSONUtils.getMorpherRegistry().registerMorpher(new TimestampMorpher(formats));  
           
            JSONObject jsonObj = JSONObject.fromObject(jsonStr);
            
            //根据对象类型
    
            Object obj = JSONObject.toBean(jsonObj,cls);
            
            return obj;
        }catch (Exception e){
            logger.error("getObjectByJsonStr json串转换成非嵌套对象失败!",e);
        }
        
        return null;
    }
    
    /**
     * 将json串转换成java对象(嵌套对象)
     * @param jsonStr
     * @param cls
     * @return
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static Object getObjectByNestJsonStr(String jsonStr,Class cls){    
        try
        {
            ObjectMapper objectMapper = new ObjectMapper();

            Object obj = objectMapper.readValue(jsonStr, cls);
            
            return obj;
        }catch (Exception e){
            logger.error("getObjectByNestJsonStr json串转换成嵌套对象失败!",e);
        }
        
        return null;
    }
    
    @SuppressWarnings("resource")
    public static void main(String[] args) {
        new ClassPathXmlApplicationContext("classpath:META-INF/spring/*-context.xml");
        
        Map<String,String> map = JedisPoolUtil.getInstance().hgetAll("0", "task:60258540182:task");
        for(String mapKey:map.keySet()){
            logger.info(mapKey+":"+ map.get(mapKey));
        }
        
        EwsTaskData ewsTaskData = new EwsTaskData();
        BeanMapConverterUtil.transMap2Bean2(map,ewsTaskData);
        logger.info(ewsTaskData.toString());
        
        String jsonStr = BeanJsonConverterUtil.getJsonStrByObject(ewsTaskData);
        logger.info(jsonStr);
        
        ewsTaskData = (EwsTaskData)BeanJsonConverterUtil.getObjectByJsonStr(jsonStr, EwsTaskData.class);
        logger.info(ewsTaskData.toString());
        
//        String key = "task:2901_134.224.136.18:taskList";
////String key = "task:" + devID + "_" + getLocalIP() + ":taskList";    
//        
////        JedisPoolUtil.getInstance().del("0", key);
//        
//        Map<String,String> scheduledTaskMap = new HashMap<String,String>();
//        if(JedisPoolUtil.getInstance().exists("0", key)){
//            scheduledTaskMap = JedisPoolUtil.getInstance().hgetAll("0", key);
//        }
//        logger.info(JedisPoolUtil.getInstance().get("0", key));
//        
//        key = "task:2901_134.224.136.18:execingtaskList";
//        
////        JedisPoolUtil.getInstance().del("0", key);
//        
//        logger.info(JedisPoolUtil.getInstance().get("0", key));
        
//        String key = "ews:60000072142916:ewsServ";
//        
////        JedisPoolUtil.getInstance().lrem("0", key, "{ews_id:60000072142916,ews_serv_code:000A,action_type:A}");
//        
//        List<String> listJsonStr = JedisPoolUtil.getInstance().lrange("0", key, 0, -1);
//        
//        for(String jsonStr : listJsonStr){
//            logger.info("jsonStr=" + jsonStr);
//            EwsServData ewsServData = (EwsServData) getObjectByJsonStr(jsonStr,EwsServData.class);
//            logger.info("ewsServData.toString()=" + ewsServData.toString());
//        }
        
//        String taskTmlKey = "task:taskToTml:queryTml";
//        
//        Map<String,String> taskTmlMap = JedisPoolUtil.getInstance().hgetAll("0", taskTmlKey);
//        logger.info("getEwsTaskDataByTaskId taskTmlMap size " + taskTmlMap.size());
//        for(String mapKey:taskTmlMap.keySet()){
//            logger.info("getEwsTaskDataByTaskId taskTmlMap info " + mapKey+"   "+ taskTmlMap.get(mapKey));
//        }
//        
//        logger.info(Integer.parseInt(taskTmlMap.get("60133363809l")) + "");
        
        
//        String jsonStr = "{ews_id:60000072142916,ews_serv_code:000A,action_type:'A'}";
//        logger.info(jsonStr);
//        EwsServData ewsServData = (EwsServData) getObjectByJsonStr(jsonStr,EwsServData.class);
//        logger.info("ewsServData.toString()=" + ewsServData.toString());
//        
//        jsonStr = getJsonStrByObject(ewsServData);
//        logger.info("jsonStr=" + jsonStr);
//        
//        JedisPoolUtil.getInstance().lpush("0", key, jsonStr);
        
//        String jsonStr = "{action_type:1,ews_para_value:111,old_ews_para_value:111,para_type:1}";
//        
//        EwsParaData ewsParaData = (EwsParaData) getObjectByJsonStr(jsonStr,EwsParaData.class);
//        logger.info("ewsParaData.toString()=" + ewsParaData.toString());
//        
//        jsonStr = getJsonStrByObject(ewsParaData);
//        logger.info("jsonStr=" + jsonStr);
    }
}


将Bean中的Timestamp转换为json中的日期字符串

public class JsonDateValueProcessor implements JsonValueProcessor {
   
    public static final String Default_DATE_PATTERN ="yyyy-MM-dd";  
    private DateFormat dateFormat ;  
    
    public JsonDateValueProcessor(String datePattern){  
        try{  
            dateFormat  = new SimpleDateFormat(datePattern);}  
        catch(Exception e ){  
            dateFormat = new SimpleDateFormat(Default_DATE_PATTERN);  
        }  
    }  
    public Object processArrayValue(Object value, JsonConfig jsonConfig) {  
        return process(value);  
    }  
    public Object processObjectValue(String key, Object value,JsonConfig jsonConfig) {  
        return process(value);  
    }  
    private Object process(Object value){ 
        try {
            if (value instanceof java.sql.Timestamp) {
                return dateFormat.format((Date)value); 
            }
            return value == null ? "" : value.toString();
        } catch (Exception e) {
            return "";
        }
    }  
    
}



你可能感兴趣的:(java对象与json串的相互转换 将Bean中的Timestamp转换为json中的日期字符串)