电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術文章
文章詳情頁

淺談Java中FastJson的使用

瀏覽:114日期:2022-08-09 15:39:07
FastJson的使用

使用maven導入依賴包

<!--下邊依賴跟aop沒關系,只是項目中用到了 JSONObject,所以引入fastjson--><dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.70</version></dependency>

常用方法:

1.JSON.toJSONString(obejct) - java對象轉JSON字符串,

注意:

默認情況下,如果int類型和boolean類型的屬性沒賦值的時候 (public boolean a; public int b;),調用 JSON.toJSONString(obejct) 序列化后,a和b不會被過濾掉,而是返回boolean類型和int類型的默認值 false和0。當然其他類型如果沒有賦值,序列化時,會被過濾掉。

來看下例子就明白了

public class Test { public static void main(String[] args) {List<User> userList = new ArrayList<>();User user = new User();user.setName('123');userList.add(user);System.out.println(JSON.toJSONString(userList)); } public static class User{private String name;private int age;public boolean health;public Date time; public String getName() { return name;} public void setName(String name) { this.name = name;} public int getAge() { return age;} public void setAge(int age) { this.age = age;} }}

先給name賦值,其他的都不賦值,結果time屬性被過濾掉了,如下:

淺談Java中FastJson的使用

再看下都不賦值的情況,結果name和time屬性都被過濾掉了,而int類型的age和boolean類型的health屬性取得時類型的默認值:

淺談Java中FastJson的使用

2.JSON.parseObject(string, User.class) - JSON字符串轉java對象

(1)List集合轉JSON

@RestControllerpublic class Json { @RequestMapping(value = '/json') public String json() throws Exception{List<User> userList = new ArrayList<>();userList.add(new User('1', '1', 20));String res = JSON.toJSONString(userList);return res; }}

淺談Java中FastJson的使用

(2)Map集合轉JSON

package com.lxc.Test; import com.alibaba.fastjson.JSON; import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map; public class Json { public static void main(String[] args) {Map<String, Object> userList = new HashMap<>();for(int i = 0; i < 5; i ++) { userList.put('user'+i, new User('name'+i, 20+i));}System.out.println('json:'+JSON.toJSONString(userList)); } public static class User{private String name;private int age; public User(String name, int age) { this.name = name; this.age = age;} public String getName() { return name;} public void setName(String name) { this.name = name;} public int getAge() { return age;} public void setAge(int age) { this.age = age;} }}

淺談Java中FastJson的使用

反序列化

1.JSON轉Java對象 - JSON.perseObject()

public class Json { public static void main(String[] args) {String json = '{'age':20,'name':'name0'}';System.out.println(JSON.parseObject(json, User.class)+''); }}

淺談Java中FastJson的使用

2.JSON轉Java集合 - JSON.perseArray()

public class Json { public static void main(String[] args) {String json = '[{'age':20,'name':'name0'}]';List<User> userList = JSON.parseArray(json, User.class);userList.forEach(System.out::println); }}

淺談Java中FastJson的使用

JSON.toJSONString() 參數 - SerializerFeature枚舉常量

toJSONString 靜態方法參數有兩個:

參數一:要序列化的對象;參數二:SerializerFeature 枚舉類型的可變參數 ( 我們可以傳遞多個參數 ),進行序列化時,我們可以定義特殊的需求。

淺談Java中FastJson的使用

1.SerializerFeature.WriteMapNullValue

對一個對象或者列表進行序列化時,默認情況下如果屬性值為null,序列化后的結果會過濾掉其屬性,如果想保留其屬性值,可以使用 SerializerFeature.WriteMapNullValue。

public class Json { public static void main(String[] args) {User user = new User();user.setAge(20);String res = JSON.toJSONString(user, SerializerFeature.WriteMapNullValue);System.out.println(res); } public static class User{private String name = null;private int age; public String getName() { return name;} public void setName(String name) { this.name = name;} public int getAge() { return age;} public void setAge(int age) { this.age = age;} @Overridepublic String toString() { return 'User{' + 'name=’' + name + ’’’ + ', age=' + age + ’}’;} }}

淺談Java中FastJson的使用

2.SerializerFeature.WriteNullStringAsEmpty

對一個對象或者列表進行序列,把屬性值為null的字段進行轉化為 '' 雙引號。

public class Json { public static void main(String[] args) {User user = new User();user.setAge(20);String res = JSON.toJSONString(user, SerializerFeature.WriteNullStringAsEmpty);System.out.println(res); }}

淺談Java中FastJson的使用

3.SerializerFeature.WriteNullNumberAsZero

序列之后, 把屬性值為 null 的屬性轉化為 0,這個前提是此屬性是 int 類型的!

public class Json { public static void main(String[] args) {User user = new User();user.setName('測試');String res = JSON.toJSONString(user, SerializerFeature.WriteNullNumberAsZero);System.out.println(res); }}

淺談Java中FastJson的使用

4.SerializerFeature.WriteNullBooleanAsFalse

序列之后, 把屬性值為 null 的屬性轉化為 false,這個前提是此屬性是 boolean 類型的!

@Datapublic class User{private String name;private int age;private boolean health;}

淺談Java中FastJson的使用

5.SerializerFeature.WriteDateUseDateFormat

把時間戳序列化為正常的時間,默認輸出JSON.toJSONString() 序列之后, 默認輸出如下:

淺談Java中FastJson的使用

添加 SerializerFeature.WriteDateUseDateFormat 之后的效果:

淺談Java中FastJson的使用

@Datapublic class User{ private String name; private int age; private Date birthday = new Date(); private boolean health;}

6.SerializerFeature.PrettyFormat

序列化的數據縱向布局。

淺談Java中FastJson的使用

@JSonField() 注解

在序列化時,進行個性定制!該注解的作用于方法上,字段上、參數上,可在序列化和反序列化時進行特性功能定制。

淺談Java中FastJson的使用

1.注解屬性 name序列化后的名字(單獨序列化,對屬性名進行修改)

@JSONField(name='username')private String name;

淺談Java中FastJson的使用

2.注解屬性 ordinal序列化后的順序(字段的排序)

@JSONField(ordinal = 1)private String name;@JSONField(ordinal = 2)private int age;

淺談Java中FastJson的使用

3.注解屬性 format 序列化后的格式

@JSONField(format = 'YYYY-MM-dd')private Date birthday = new Date();

淺談Java中FastJson的使用

4.注解屬性 serialize 是否序列化該字段(默認為true,如果false,當字段值為null時,會被過濾掉)

5.使用serializeUsing來定制屬性的序列化類

淺談Java中FastJson的使用

什么意思呢,類似vue中的過濾器,可以單獨訂制處理類下的某個屬性:

第一步:編寫一個類A,實現ObjectSerializer 接口;第二步:重寫write方法;第三步:在需要定制化的屬性上邊 添加注解,@JSONField(serializeUsing = A.class)

具體實現如下:

public class Json { public static void main(String[] args) {List<User> userList = new ArrayList<>();User user = new User();user.setName('測試,');userList.add(user);System.out.println(JSON.toJSONString(userList)); } public static class SerializeUsingFn implements ObjectSerializer { @Overridepublic void write(JSONSerializer jsonSerializer, Object fieldValue, Object fieldName, Type fieldType, int i) throws IOException { System.out.println(fieldValue); // 測試, System.out.println(fieldName); // name System.out.println(fieldType); // String System.out.println(i); // 0 String name = (String) fieldValue; // 向下轉型,獲取到age屬性值 String filterName = name + '呵呵'; // 這里可以對name屬性進行定制化 jsonSerializer.write(filterName); // 調用write方法} } public static class User{@JSONField(serializeUsing = SerializeUsingFn.class)private String name;private int age;public boolean health;public Date time; public String getName() { return name;} public void setName(String name) { this.name = name;} public int getAge() { return age;} public void setAge(int age) { this.age = age;} }}

可以看到name字段值 被修改了后邊添加了 '呵呵' 倆字。

淺談Java中FastJson的使用

@JSONType() 注解

只能作用在類上,也是對類里邊的字段進行序列化

淺談Java中FastJson的使用

@JSONType()注解中的屬性

· includes 要序列化的字段(注意:如果字段上有 @serialize(true),如果沒有includes字段也不會被序列化),它是一個數組,源碼如下:

淺談Java中FastJson的使用

@Data@JSONType(includes = {'name', 'age'})public class User{ private String name; private int age; private boolean health; private Date birthday = new Date();}

淺談Java中FastJson的使用

· orders序列化后的字段順序,也是一個數組,源碼如下:

淺談Java中FastJson的使用

@JSONType(includes = {'name','birthday', 'health', 'age'}, orders = {'age','name','birthday','health'})public static class User{ private String name; private int age; private boolean health; private Date birthday = new Date();}

淺談Java中FastJson的使用

FastJson屬性名過濾器

過濾字段,通過 SimplePropertyPreFilter 過濾器,來過濾指定的屬性名,然后在轉JSON的時候,帶上過濾器參數即可。例如,把下邊屬性health 過濾掉:

// userList = [{'age':20,'health':true,'name':'測試,呵呵','time':'2021-06-29 09:40:55'}] SimplePropertyPreFilter filter = new SimplePropertyPreFilter();// 下邊方法也很好理解:調用過濾器上邊的getExcludes排除字段的方法,什么字段需要排除呢:add() 添加需要排除的字段即可filter.getExcludes().add('health');System.out.println(JSON.toJSONString(userList, filter));

淺談Java中FastJson的使用

當然,如果需要排除大量的字段,保留一個字段,可以使用:filter.getIncludes() .add('xxx') 方法,意思:只保留xxx屬性,其他的都會被過濾。

如果過濾或者添加多個字段,可以使用:addAll() 方法,參數必須是一個集合Collection 。

淺談Java中FastJson的使用

過濾多個字段:

SimplePropertyPreFilter filter = new SimplePropertyPreFilter();List<String> r = new ArrayList<>() { {add('health');add('name'); }};filter.getExcludes().addAll(r);System.out.println(JSON.toJSONString(userList, filter));

淺談Java中FastJson的使用

暫時就這么多,項目中用到別的方法在記錄!

到此這篇關于淺談Java中FastJson的使用的文章就介紹到這了,更多相關FastJson的使用內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Java
相關文章:
主站蜘蛛池模板: 铝机箱_铝外壳加工_铝外壳厂家_CNC散热器加工-惠州市铂源五金制品有限公司 | 哈尔滨治「失眠/抑郁/焦虑症/精神心理」专科医院排行榜-京科脑康免费咨询 一对一诊疗 | 轴流风机-鼓风机-离心风机-散热风扇-罩极电机,生产厂家-首肯电子 | 卓能JOINTLEAN端子连接器厂家-专业提供PCB接线端子|轨道式端子|重载连接器|欧式连接器等电气连接产品和服务 | 减速机三参数组合探头|TSM803|壁挂式氧化锆分析仪探头-安徽鹏宸电气有限公司 | led太阳能路灯厂家价格_风光互补庭院灯_农村市政工程路灯-中山华可路灯品牌 | 包头市鑫枫装饰有限公司| 哈希余氯测定仪,分光光度计,ph在线监测仪,浊度测定仪,试剂-上海京灿精密机械有限公司 | 光谱仪_积分球_分布光度计_灯具检测生产厂家_杭州松朗光电【官网】 | 箱式破碎机_移动方箱式破碎机/价格/厂家_【华盛铭重工】 | 壹车网 | 第一时间提供新车_资讯_报价_图片_排行! | 蜜蜂职场文库_职场求职面试实用的范文资料大全 | 【德信自动化】点胶机_全自动点胶机_自动点胶机厂家_塑料热压机_自动螺丝机-深圳市德信自动化设备有限公司 | 旋振筛|圆形摇摆筛|直线振动筛|滚筒筛|压榨机|河南天众机械设备有限公司 | 打包钢带,铁皮打包带,烤蓝打包带-高密市金和金属制品厂 | 网站制作优化_网站SEO推广解决方案-无锡首宸信息科技公司 | 鄂泉泵业官网|(杭州、上海、全国畅销)大流量防汛排涝泵-LW立式排污泵 | 昆山PCB加工_SMT贴片_PCB抄板_线路板焊接加工-昆山腾宸电子科技有限公司 | 阴离子聚丙烯酰胺价格_PAM_高分子聚丙烯酰胺厂家-河南泰航净水材料有限公司 | 工控机-工业平板电脑-研华工控机-研越无风扇嵌入式box工控机 | MTK核心板|MTK开发板|MTK模块|4G核心板|4G模块|5G核心板|5G模块|安卓核心板|安卓模块|高通核心板-深圳市新移科技有限公司 | 比亚迪叉车-比亚迪电动叉车堆垛车托盘车仓储叉车价格多少钱报价 磁力去毛刺机_去毛刺磁力抛光机_磁力光饰机_磁力滚抛机_精密金属零件去毛刺机厂家-冠古科技 | 领袖户外_深度旅游、摄影旅游、小团慢旅行、驴友网 | 【铜排折弯机,钢丝折弯成型机,汽车发泡钢丝折弯机,线材折弯机厂家,线材成型机,铁线折弯机】贝朗折弯机厂家_东莞市贝朗自动化设备有限公司 | 「钾冰晶石」氟铝酸钾_冰晶石_氟铝酸钠「价格用途」-亚铝氟化物厂家 | 宜兴市恺瑞德环保科技有限公司| 数码听觉统合训练系统-儿童感觉-早期言语评估与训练系统-北京鑫泰盛世科技发展有限公司 | 二手Sciex液质联用仪-岛津气质联用仪-二手安捷伦气质联用仪-上海隐智科学仪器有限公司 | 硫酸亚铁-聚合硫酸铁-除氟除磷剂-复合碳源-污水处理药剂厂家—长隆科技 | 半自动预灌装机,卡式瓶灌装机,注射器灌装机,给药器灌装机,大输液灌装机,西林瓶灌装机-长沙一星制药机械有限公司 | 杭州货架订做_组合货架公司_货位式货架_贯通式_重型仓储_工厂货架_货架销售厂家_杭州永诚货架有限公司 | 不锈钢/气体/液体玻璃转子流量计(防腐,选型,规格)-常州天晟热工仪表有限公司【官网】 | 贵阳用友软件,贵州财务软件,贵阳ERP软件_贵州优智信息技术有限公司 | 甲级防雷检测仪-乙级防雷检测仪厂家-上海胜绪电气有限公司 | 智能汉显全自动量热仪_微机全自动胶质层指数测定仪-鹤壁市科达仪器仪表有限公司 | 广域铭岛Geega(际嘉)工业互联网平台-以数字科技引领行业跃迁 | 发电机价格|发电机组价格|柴油发电机价格|柴油发电机组价格网 | 碳化硅,氮化硅,冰晶石,绢云母,氟化铝,白刚玉,棕刚玉,石墨,铝粉,铁粉,金属硅粉,金属铝粉,氧化铝粉,硅微粉,蓝晶石,红柱石,莫来石,粉煤灰,三聚磷酸钠,六偏磷酸钠,硫酸镁-皓泉新材料 | 清洁设备_洗地机/扫地机厂家_全自动洗地机_橙犀清洁设备官网 | 上海洗地机-洗地机厂家-全自动洗地机-手推式洗地机-上海滢皓洗地机 | 玉米深加工设备|玉米加工机械|玉米加工设备|玉米深加工机械-河南成立粮油机械有限公司 |