package com.ruoyi.common.utils;
|
|
import java.math.BigDecimal;
|
import java.util.Date;
|
import java.util.Map;
|
|
import com.ruoyi.common.utils.DateUtils;
|
|
/**
|
* Map值转换工具类
|
* 提供从Map中安全获取各种类型值的方法
|
*
|
* @author ruoyi
|
*/
|
public class MapValueUtils {
|
|
/**
|
* 从Map中获取字符串值
|
*
|
* @param map Map对象
|
* @param key 键
|
* @return 字符串值,如果键不存在或值为null则返回null
|
*/
|
public static String getStringValue(Map<String, Object> map, String key) {
|
Object value = map.get(key);
|
return value != null ? value.toString() : null;
|
}
|
|
/**
|
* 从Map中获取BigDecimal值
|
*
|
* @param map Map对象
|
* @param key 键
|
* @return BigDecimal值,如果键不存在或值为null则返回null,转换失败也返回null
|
*/
|
public static BigDecimal getBigDecimalValue(Map<String, Object> map, String key) {
|
Object value = map.get(key);
|
if (value == null) {
|
return null;
|
}
|
if (value instanceof BigDecimal) {
|
return (BigDecimal) value;
|
}
|
try {
|
return new BigDecimal(value.toString());
|
} catch (NumberFormatException e) {
|
return null;
|
}
|
}
|
|
/**
|
* 从Map中获取Long值
|
*
|
* @param map Map对象
|
* @param key 键
|
* @return Long值,如果键不存在或值为null则返回null,转换失败也返回null
|
*/
|
public static Long getLongValue(Map<String, Object> map, String key) {
|
Object value = map.get(key);
|
if (value == null) {
|
return null;
|
}
|
if (value instanceof Long) {
|
return (Long) value;
|
}
|
try {
|
return Long.valueOf(value.toString());
|
} catch (NumberFormatException e) {
|
return null;
|
}
|
}
|
|
/**
|
* 从Map中获取Integer值
|
*
|
* @param map Map对象
|
* @param key 键
|
* @return Integer值,如果键不存在或值为null则返回null,转换失败也返回null
|
*/
|
public static Integer getIntegerValue(Map<String, Object> map, String key) {
|
Object value = map.get(key);
|
if (value == null) {
|
return null;
|
}
|
if (value instanceof Integer) {
|
return (Integer) value;
|
}
|
try {
|
return Integer.valueOf(value.toString());
|
} catch (NumberFormatException e) {
|
return null;
|
}
|
}
|
|
/**
|
* 从Map中获取Date值
|
*
|
* @param map Map对象
|
* @param key 键
|
* @return Date值,如果键不存在或值为null则返回null,如果是字符串会尝试解析
|
*/
|
public static Date getDateValue(Map<String, Object> map, String key) {
|
Object value = map.get(key);
|
if (value == null) {
|
return null;
|
}
|
if (value instanceof Date) {
|
return (Date) value;
|
}
|
// 如果是字符串,尝试解析
|
if (value instanceof String) {
|
try {
|
return DateUtils.parseDate(value.toString());
|
} catch (Exception e) {
|
return null;
|
}
|
}
|
return null;
|
}
|
|
/**
|
* 验证日期字符串格式是否有效
|
*
|
* @param dateStr 日期字符串
|
* @param format 日期格式
|
* @return 是否有效
|
*/
|
public static boolean isValidDateFormat(String dateStr, String format) {
|
if (StringUtils.isEmpty(dateStr)) {
|
return false;
|
}
|
|
try {
|
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(format);
|
sdf.setLenient(false);
|
sdf.parse(dateStr);
|
return true;
|
} catch (Exception e) {
|
return false;
|
}
|
}
|
}
|