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

概述

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/Kotlin TypeAdapter
Moshi 反射/注解 Java/Kotlin JsonAdapter
KS 编译插件 Kotlin KSerializer

基本用法之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()

猜你喜欢

转载自blog.csdn.net/weixin_38364803/article/details/84865229