首页 > Web开发 > 详细

json字符串转Map

时间:2020-02-19 17:09:24      阅读:57      评论:0      收藏:0      [点我收藏+]
 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);

 

json字符串转Map

原文:https://www.cnblogs.com/zk-blog/p/12331612.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!