当前位置:网站首页>Encapsulation of conversion between Json and objects (Gson)
Encapsulation of conversion between Json and objects (Gson)
2022-07-31 12:07:00 【wresource】
I. Preface
Some time ago, due to the backend of spring boot, it was often necessary to convert between Json and objects, so using Gson combined with the characteristics of Kotlin extension functions to encapsulate two very convenient functions, if it is in other languages, it can also be encapsulatedFor a moment, it is not convenient without Kotlin.The following shows the final packaging effect
Object to Json
val cat = Cat()cat.toMyJson()
Json to Object
//Single object, here it needs to be converted into a single object manually, mainlyis an example of a unified formval cat = Cat()val data = cat.toMyJson()data.toMyObject()[0]//list typeval cats = List()val dataList = cats.toMyObject()[0]
2. Object to Json
This needs to be extended under Any. Since Any is the parent class of all classes, this is somewhat similar to Object in Java
fun Any.toMyJson():String{return Gson().toJson(this)}
It can be used directly after encapsulation. Gson is not so difficult to deal with, but only the way of writing points saves the time of bracketing
val cat = Cat()cat.toMyJson()
Three, Json transfer object
This is a bit problematic when encapsulating it at first. First of all, it is easier to find the extended object, which is the String type, but there is one thing that needs to be paid attention to. Here, the reflection mechanism is used for Gson conversion, so two processes need to be done
- Generic materialization processing
- Dealing with reflection-related issues
Final code effect
inline fun String.toMyObject(): List {val listType: Type = `$Gson$Types`.newParameterizedTypeWithOwner(null, ArrayList::class.java, T::class.java)return if(!contains("[")){Gson().fromJson("[${this}]", listType)}else{Gson().fromJson(this, listType)}}
Use of packaging
val cat = Cat()val data = cat.toMyJson()data.toMyObject()[0]
However, there is a disadvantage here that if it is a single object, you need to manually take the first value as the object, because the return value is of the list type. If there is a way to change the return value type, please leave a message in the comment area
/p>
Fourth, issues that need attention
Object to Json needs attention
This only needs to pay attention to the format after conversion, list or single object can be directly converted
Json to object needs attention
What needs to be noted is that the type of the object should be clear, and the non-Json format string cannot be converted successfully, although it has this method, and then my current plan is to convert it into a unified list type, so you need to manually get the value
V. Summary
It was quite a headache when I encountered these before, and I often needed to go back and forth. Many articles on the Internet did not explain it clearly. Although the packaged library is only a few lines of code, in short, convenient development is the bestYes, the simpler the better.
边栏推荐
- Android studio connects to MySQL and completes simple login and registration functions
- 一周精彩内容分享(第14期)
- 字符函数和字符串函数
- Different lower_case_table_names settings for server (‘1‘) and data dictionary (‘0‘) 解决方案
- busybox之reboot命令流程分析
- Redis学习笔记-3.慢查询和其他高级数据结构
- 文件包含漏洞
- AWS Amazon cloud account registration, free application for 12 months Amazon cloud server detailed tutorial
- Getting started with jmeter performance testing steps (performance testing tool jmeter)
- 科学论文和学术论文写作
猜你喜欢
MySQL日志中“binlog”的三种格式玩起来真爽
Selenium自动化测试之Selenium IDE
Android studio connects to MySQL and completes simple login and registration functions
Acwing第 62 场周赛【未完结】
Docker installs canal and mysql for simple testing and achieves cache consistency between redis and mysql
Full GC (Ergonomics)排查分析
Exploring Plain Vision Transformer Backbones for Object Detection 论文阅读笔记
Candence学习篇(11) allegro中设置规则,布局,走线,铺铜
chroot命令
JVS设置不同应用的登录时效时间
随机推荐
Comparison of ipv4 and ipv6 (IPV4)
一周精彩内容分享(第14期)
MySQL index usage and optimization
线性表的基本概念
Hybrid brain-computer interface system based on steady-state visual evoked potentials and attentional EEG
Use ODBC in Excel to read data from CDS view on SAP BTP platform
Docker build Mysql master-slave replication
am335x 看门狗驱动&看门狗应用例程序
ApiPost is really fragrant and powerful, it's time to throw away Postman and Swagger
Standard SQL/JSON - the sobering part
Docker installs canal and mysql for simple testing and achieves cache consistency between redis and mysql
R 语言data.frame 中的另一行中减去一行
榕树贷款GPU 硬件架构
最近两个月谷歌 ad 掉的厉害
MySQL日志中“binlog”的三种格式玩起来真爽
DCM 中间件家族迎来新成员
St. Regis Takeaway Project: New dishes and dishes paged query
JVS设置不同应用的登录时效时间
三相PWM整流器预测直接功率控制
Experience innovation and iteration through the development of lucky draw mini-programs