博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java中使用FastJSON进行对象的序列化和反序列化
阅读量:6990 次
发布时间:2019-06-27

本文共 6564 字,大约阅读时间需要 21 分钟。

Java中使用FastJSON进行对象的序列化和反序列化

1.添加依赖,maven的pom.xml文件中添加以下依赖

com.alibaba
fastjson
1.2.47

2.FastJSON序列化和反序列化工具类

import java.util.List;import com.alibaba.fastjson.JSONArray;import com.alibaba.fastjson.JSONObject;// JSON/对象转换类public class JsonUtils {    /**     * JSON字符串转换成对象     */    public static 
T jsonStringToObject(String jsonStr,Class
obj){ try{ return JSONObject.parseObject(jsonStr, obj); }catch(Exception e){ System.out.println("将JSON串{}转换成 指定对象失败:"+jsonStr); e.printStackTrace(); } return null; } /** * 对象转JSON */ public static
String objectToJson(T obj){ try{ String json=JSONObject.toJSONString(obj); return json; }catch(Exception e){ System.out.println("将指定对象转成JSON串{}失败:"+obj.toString()); e.printStackTrace(); } return ""; } /** * List
对象转成json */ public static
String listToJsonString(List
objList){ try{ String json=JSONObject.toJSONString(objList); return json; }catch(Exception e){ System.out.println("将对象列表转成JSON串{}失败:"+objList.toString()); e.printStackTrace(); } return ""; } /** * json转换成对象列表List
*/ public static
List
jsonStringToList(String json,Class
obj){ try{ return JSONArray.parseArray(json, obj); }catch(Exception e){ System.out.println("将JSON串{}转成对象列表失败:"+json); e.printStackTrace(); } return null; } /* * 将JSON串转换为JSONOBJECT */ public static JSONObject stringTOJSONObject(String json){ JSONObject jsonObject = null; try { jsonObject = JSONObject.parseObject(json); } catch (Exception e) { System.out.println("JSON串{} 转换成 JsonObject失败"+json); } return jsonObject; }}

3.使用

(1)序列化

List
users=new ArrayList
(); for(int i=0;i<20;i++){ User user=new User(); user.setName("FastJSON"+i); user.setAge(20+i); SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd"); user.setBirthday(dateformat.parse("1991-10-01")); user.setEmail("12345678"+i+"@qq.com"); // 序列化单个对象 String json=JsonUtils.objectToJson(user); users.add(user); // 序列化对象列表 // String json=JsonUtils.listToJsonString(users);}

(2)反序列化

// 反序列化单个对象        User u=JsonUtils.jsonStringToObject(json, User.class);        System.out.println(u.toString());        // 将JSON串转换为JSONOBJECT        JSONObject js=JsonUtils.stringTOJSONObject(json);        System.out.println(js);        // 反序列化对象列表        List
list=JsonUtils.jsonStringToList(json, User.class); System.out.println(list);

4.FastJson的常见操作

(1)日期进行格式化    String dateToJson=JSON.toJSONString(new Date(), SerializerFeature.WriteDateUseDateFormat);    System.out.println("使用JSON中的SerializerFeature特性格式化日期:"+dateToJson);    String dateToJson2=JSON.toJSONStringWithDateFormat(new Date(), "yyyy/MM/dd");    System.out.println("JSON中自定义日期的输出格式:"+dateToJson2);    (2)将Map转换成JSONObject然后添加元素,最后输出。    Map
map = new HashMap
(); map.put("name", "Gelpe"); map.put("age", 30); map.put("brithday",dateToJson); map.put("date",dateToJson2); // 将Map对象转成JSON字符串 String mapToJson=JSON.toJSONString(map); System.out.println("将MAP转成JSON: :"+mapToJson); // 将Map转换成JSONObject对象 JSONObject jsonObject = new JSONObject(map); System.out.println("JSONObject 1:"+jsonObject); (3)List转成JSON List
list=new ArrayList
(); list.add("shopping"); list.add("travel"); String listToJson=JSON.toJSONString(list); System.out.println("将List中存储的字符串转成JSON: :"+listToJson); (4) 向JSONObject中添加值 jsonObject.put("hobbies",list); (5) 从JSONObject中取值 System.out.println(jsonObject.get("hobbies")); System.out.println("JSONObject 2:"+jsonObject); (6)将List对象转成JSONArray,然后输出 List
> mapList=new ArrayList
>(); Map
map3 = new HashMap
(); map3.put("address", "Beijing"); map3.put("city", "Beijing"); Map
map4 = new HashMap
(); map4.put("town", "wulukou"); map4.put("street", "Four street"); mapList.add(map3); mapList.add(map4); String listMapToJson=JSON.toJSONString(mapList); System.out.println("将List中存储的MAP对象转成JSON:"+listMapToJson); (7)JSON格式化输出 // 第二个参数true表示是否格式化输出 String listMapToJson2=JSON.toJSONString(mapList, true); System.out.println("将List中存储的MAP对象转成JSON并且格式化输出:"+listMapToJson2); (8) 将List对象转成JSONArray JSONArray jsonArray=JSONArray.parseArray(JSON.toJSONString(mapList)); System.out.println("JSONArray:"+jsonArray); (9)打印JSONArray中的内容 for(int i=0;i

以上操作,输出的内容:

使用JSON中的SerializerFeature特性格式化日期:"2018-12-01 10:58:46"JSON中自定义日期的输出格式:"2018/12/01"将MAP转成JSON: :{"date":"\"2018/12/01\"","brithday":"\"2018-12-01 10:58:46\"","name":"Gelpe","age":30}JSONObject 1:{"date":"\"2018/12/01\"","brithday":"\"2018-12-01 10:58:46\"","name":"Gelpe","age":30}将List中存储的字符串转成JSON: :["shopping","travel"][shopping, travel]JSONObject 2:{"date":"\"2018/12/01\"","hobbies":["shopping","travel"],"brithday":"\"2018-12-01 10:58:46\"","name":"Gelpe","age":30}将List中存储的MAP对象转成JSON:[{"address":"Beijing","city":"Beijing"},{"town":"wulukou","street":"Four street"}]将List中存储的MAP对象转成JSON并且格式化输出:[    {        "address":"Beijing",        "city":"Beijing"    },    {        "town":"wulukou",        "street":"Four street"    }]JSONArray:[{"address":"Beijing","city":"Beijing"},{"town":"wulukou","street":"Four street"}]JSONArray Content:{"address":"Beijing","city":"Beijing"}JSONArray Content:{"town":"wulukou","street":"Four street"}JSONObject 3:{"date":"\"2018/12/01\"","addressInfo":[{"address":"Beijing","city":"Beijing"},{"town":"wulukou","street":"Four street"}],"hobbies":["shopping","travel"],"brithday":"\"2018-12-01 10:58:46\"","name":"Gelpe","age":30}自定义对象转成JSON:{"age":24,"birthday":1543648393681,"name":"NB Person"}

JSON的解析:

(1)集合反序列化            Map
map=JSON.parseObject(jsonString, Map.class); System.out.println("map get name:"+map.get("name")); System.out.println("map:"+map);(2)泛型的反序列化,使用TypeReference传入类型信息 Map
map2=JSON.parseObject((jsonString,new TypeReference
>(){}); System.out.println("map2 get name:"+map2.get("name")); System.out.println("map2 get hobbies:"+map2.get("hobbies")); System.out.println("map2:"+map2);

转载于:https://blog.51cto.com/59465168/2324480

你可能感兴趣的文章