当前位置:网站首页>Android:kotlin中Gson与JSON的泛型映射解析
Android:kotlin中Gson与JSON的泛型映射解析
2022-06-25 10:25:00 【奔跑的蜗牛、Z】
背景:
在Android中,kotlin的使用,可以极大美化代码和带来代码上的简洁,但是kotlin之前,android的主要语言是Java。
在android中,解析数据是比较常见的手法。JavaBean,GSON,JSONOBJECT,这三大员是合作伙伴,但是在kotlin中依然支持这种写法,但是kotlin的data GSON,JSONOBJECT,与Java解析有所不同
Java:
People{
private String name="";
private String sex="";
public void setName(String name)
{
this.name=name
}
public void setSex(String sex){
this.sex=sex;
}
public String getName(){
return name;
}
public String getSex()
{
return sex;
}
}
Json:{"name":"zhangshan","sex":"男"}
解析如下
People people=new Gson().fromJson(json,People.class);
这是Java的解析。
kotlin:
kotlin的解析与Java不同,JavaBean在kotlin中叫数据data
data class People(var name:String="",var sex:String="");
或者直接定义一个class类也行
class People{
var name:String=""
var sex:String=""
}
解析GSON:
我们在做解析最好能做到通用,所以在做解析工具有点不同,如下
object GsonUtil {
public inline fun <reified T> getGsonObject(json: String): T? {
val result = Gson().fromJson<T>(json)
return result
}
//type 泛型扩展
inline fun <reified T> Gson.fromJson(json: String) = this.fromJson<T>(json, object : TypeToken<T>() {}.type)
}GSON在kotlin的最大泛型处理在于type部分,所以我们在内部通过扩展函数,对Gson.fromJson进行扩展,这样我们就可以直接使用方法参数泛型解析。
这里面不同于Java的函数泛型,kotlin支持方法泛型。
总结:
不同在于bean的定义,kotlin中叫data class
边栏推荐
- Houdini graphic notes: could not create OpenCL device of type (houdini_ocl_devicetype) problem solving
- Modbus protocol and serialport port read / write
- Kotlin implements a simple login page
- 【RPC】I/O模型——BIO、NIO、AIO及NIO的Rector模式
- 之前字符串反转的题目
- ES 学习
- Comparison and evaluation of digicert and globalsign single domain ov SSL certificates
- Oracle彻底卸载的完整步骤
- QT: parsing JSON
- The left sliding menu +menu item icon is grayed out
猜你喜欢

Flask博客实战 - 实现侧边栏文章归档及标签

Your driver settings have been set to force 4x antialiasing in OpenGL applications

无心剑中译伊玛·拉扎罗斯《新巨人·自由女神》

Use of Siemens plcs7-200 (I) -- Introduction to development environment and configuration software

Create menu file

Binder explanation of Android interview notes

String implementation strstr()

What is CRA

1-7snapshots and clones in VMWare

浅谈二叉树
随机推荐
OODA working method
String longest common prefix
keep-alive
On binary tree
CSRF attack
CSRF攻击
垃圾回收机制
Request&Response有这一篇就够了
DDS learning notes of opendds
Ouverture de l'inscription | le troisième marathon des hackers de pagaie est arrivé comme prévu.
XSS attack
I hope to explain the basics of canvas as clearly as possible according to my ideas
国信证券证券账户开户安全吗
I have summarized the knowledge points of JS [intermediate and advanced] for you
戴尔科技演绎“快”字诀,玩转CI/CD
NETCORE performance troubleshooting
Think about it
DigiCert和GlobalSign单域名OV SSL证书对比评测
Flask blog practice - realize the latest articles and search in the sidebar
【图像融合】基于形态学分析结合稀疏表征实现图像融合附matlab代码