JSON字符串对象互转
本次测试使用
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.51</version></dependency>
1、对象转JSON字符串
Order<String> order = new Order<>();
String s = JSON.toJSONString(order);
2、JSON字符串转对象
1)JSONObject jsonObject = JSONObject.parseObject(s);2)Order<T> order1 = JSONObject.parseObject(s,new TypeReference<Order<T>>((Type)String.class){});
3)Order<String> order2 = JSONObject.parseObject(s,new TypeReference<Order<String>>(){});
(2)(3)效果相同可支持多层泛型,某些场景我们不知道具体泛型需要反射得到Type[]后使用(2)方法,使用参数时注意指定泛型T,花费很长时间才找到问题。若是集合使用JSONArray
Type[] types = method.getGenericParameterTypes();ParameterizedType pt = (ParameterizedType)types[0];Type type = pt.getActualTypeArguments()[0];Order<T> order = JSONObject.parseObject(s, new TypeReference<Order<T>>(type){});
3、java对象转JSON对象
JSONObject jsonObject = (JSONObject) JSONObject.toJSON(order);若是集合使用JSONArray
相关推荐
WebVincent 2020-07-21
fengchao000 2020-07-04
baijinswpu 2020-06-28
88483063 2020-06-28
fengchao000 2020-06-16
somebodyoneday 2020-06-15
wujiajax 2020-06-14
somebodyoneday 2020-05-16
xx0cw 2020-05-16
newthon 2020-05-14
sailxu00 2020-04-27
fengchao000 2020-04-20
88483063 2020-01-29
83163452 2020-01-28
baijinswpu 2020-01-25
baijinswpu 2020-01-18
fengchao000 2020-01-02