1 import java.lang.reflect.InvocationTargetException; 2 import java.util.Date; 3 import java.util.HashMap; 4 import java.util.Map; 5 6 import org.apache.commons.beanutils.BeanUtils; 7 import org.apache.commons.beanutils.ConvertUtils; 8 import org.apache.commons.beanutils.converters.BooleanConverter; 9 import org.apache.commons.beanutils.converters.DateConverter; 10 import org.apache.commons.beanutils.converters.DoubleConverter; 11 import org.apache.commons.beanutils.converters.IntegerConverter; 12 import org.apache.commons.beanutils.converters.LongConverter; 13 14 import com.common.consts.CommonBaseMessageCodeEnum; 15 import com.common.exception.BaseException; 16 import com.rabbitmq.tools.json.JSONReader; 17 import com.rabbitmq.tools.json.JSONWriter; 18 19 /** 20 * Created by xh on 2019/3/15. 21 */ 22 public abstract class JsonUtil { 23 24 private static JSONWriter jsonWriter = new JSONWriter(); 25 private static JSONReader jsonReader = new JSONReader(); 26 27 public static String object2Json(Object object) { 28 return jsonWriter.write(object); 29 } 30 31 public static Object json2Object(String json) { 32 return jsonReader.read(json); 33 } 34 35 private JsonUtil() { 36 37 } 38 39 public static <T> T json2T(String json, Class<T> clazz) throws InvocationTargetException, IllegalAccessException, InstantiationException, BaseException { 40 AssertUtil.isNotEmpty(json, CommonBaseMessageCodeEnum.REQ_PARAM_NOT_NULL); 41 Map<String, Object> map = (HashMap<String, Object>) JsonUtil.json2Object(json); 42 T t = clazz.newInstance(); 43 ConvertUtils.register(new DateConverter(), Date.class); 44 ConvertUtils.register(new LongConverter(null), Long.class); 45 ConvertUtils.register(new BooleanConverter(null), Boolean.class); 46 ConvertUtils.register(new IntegerConverter(null), Integer.class); 47 ConvertUtils.register(new DoubleConverter(null), Double.class); 48 BeanUtils.populate(t, map); 49 return t; 50 } 51 52 }
使用方式:
Map<String, Object> map = (HashMap<String, Object>) JsonUtil.json2Object(jsonStr);
原文:https://www.cnblogs.com/zk-blog/p/12331612.html