新一代Json解析库Moshi使用及原理解析

Moshi是由Square公司于2015年开源的一款用于Json反序列化及序列化的框架,相较于Gson、FastJson和Jackson,Moshi在Kotlin环境下表现出更强的适应性和性能优势。本文将介绍Moshi的基本使用方法,包括依赖配置、Java与Kotlin环境下的数据类解析,以及List和Map类型的序列化与反序列化操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

概述

Moshi是Square公司在2015年6月开源的有关Json的反序列化及序列化的框架,说到Json,大家应该很快想到Gson,FastJson以及Jackson等著名的开源框架,那为什么还需要Moshi呢?这个主要是由于Kotlin的缘故,我们知道前面说到的几大解析库主要是针对Java解析Json的,当然他们也支持Kotlin,但是Moshi天生对Kotlin友好,而且对Java的解析也毫不逊色,所以不管是在Java跟Kotlin的混编还是在纯Kotlin项目中,Moshi表现都很出色。

作者:wustor
链接:https://juejin.im/post/5bdf159251882516e246ad75
来源:掘金

性能对比

在性能对比之前,我们先简单对比下这几种解析框架的解析方式

Method支持语言自定义解析
Gson反射Java/KotlinTypeAdapter
Moshi反射/注解Java/KotlinJsonAdapter
KS编译插件KotlinKSerializer
基本用法之Java
Dependency
implementation 'com.squareup.moshi:moshi:1.8.0'
Bean
String json = ...;
Moshi moshi = new Moshi.Builder().build();
JsonAdapter<Bean> jsonAdapter = moshi.adapter(Bean.class);
//Deserialize 
Bean bean = jsonAdapter.fromJson(json);
//Serialize
String json = jsonAdapter.toJson(bean);
List
Moshi moshi = new Moshi.Builder().build();
Type listOfCardsType = Types.newParameterizedType(List.class, Bean.class);
JsonAdapter<List<Bean>> jsonAdapter = moshi.adapter(listOfCardsType);
//Deserialize 
List<Bean> beans = jsonAdapter.fromJson(json);
//Serialize
String json = jsonAdapter.fromJson(json);
Map
Moshi moshi = new Moshi.Builder().build();
ParameterizedType newMapType = Types.newParameterizedType(Map.class, String.class, Integer.class);
JsonAdapter<Map<String,Integer>> jsonAdapter = moshi.adapter(newMapType);
//Deserialize 
Map<String,Integer> beans = jsonAdapter.fromJson(json);
//Serialize
String json = jsonAdapter.fromJson(json);
基本用法之Kotlin
Reflection
Data类
data class ConfigBean(
  var isGood: Boolean = false,
  var title: String = "",
  var type: CustomType = CustomType.DEFAULT
)
开始解析
val moshi = Moshi.Builder()
    .add(KotlinJsonAdapterFactory())
    .build()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值