当前位置:网站首页>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.
边栏推荐
- [core]-ARMV7-A, ARMV8-A, ARMV9-A Architecture Introduction "Recommended Collection"
- Life is endless, there are more questions, simple questions to learn knowledge points
- Distributed Transactions - Introduction to Distributed Transactions, Distributed Transaction Framework Seata (AT Mode, Tcc Mode, Tcc Vs AT), Distributed Transactions - MQ
- WebGL给Unity传递参数问题1: Cannot read properties of undefined (reading ‘SendMessage‘)
- 给你一个大厂面试的机会,你能面试上吗?进来看看!
- Read through the interface to call the artifact RestTemplate
- Service discovery of kubernetes
- 一文吃透接口调用神器RestTemplate
- Experience innovation and iteration through the development of lucky draw mini-programs
- kubernetes之服务发现
猜你喜欢
随机推荐
How to correctly write the binary stream of the file returned by the server to the local file and save it as a file
Different lower_case_table_names settings for server (‘1‘) and data dictionary (‘0‘) 解决方案
R语言做面板panelvar例子
栈和队列的基本概念
普林斯顿微积分读本03第二章--编程实现函数图像绘制、三角学回顾
最近两个月谷歌 ad 掉的厉害
数据湖(十九):SQL API 读取Kafka数据实时写入Iceberg表
Quickly learn database management
MySQL index usage and optimization
在 Excel 里使用 ODBC 读取 SAP BTP 平台上 CDS view 的数据
After Effects 教程,如何在 After Effects 中修复曝光不足的镜头?
基于姿态估计的护具佩戴检测与动作识别
使用 Excel 读取 SAP ABAP CDS View 通过 ODBC 暴露出来的数据
如何正确地把服务器端返回的文件二进制流写入到本地保存成文件
文件包含漏洞
SAP Commerce Cloud Product Review 的添加逻辑
MySQL百万数据优化总结 一
Three-tier architecture service, dao, controller layer
dosbox基础使用[通俗易懂]
音视频基础









