背景
在深度使用 Flutter 开发过程中,我们遇到了业务代码耦合严重,代码可维护性糟糕,如入泥泞。我们需要一个统一的应用框架来摆脱当下的开发困境,而这也是 Flutter 领域空缺的一块处女地。
Fish Redux 是为解决上面问题上层应用框架,它是一个基于 Redux 数据管理的组装式 flutter 应用框架, 特别适用于构建中大型的复杂应用。
它的最大特点是配置式组装, 一方面将一个大的页面,对视图和数据层层拆解为互相独立的 Component|Adapter,上层负责组装,下层负责实现,另一方面将 Component|Adapter 拆分为 View,Reducer,Effect 等相互独立的上下文无关函数。所以它会非常干净,易编写、易维护、易协作。
Fish Redux 的灵感主要来自于 Redux、React、Elm、Dva 这样的优秀框架,而 Fish Redux 站在巨人的肩膀上,将集中,分治,复用,隔离做的更进一步。
}
return type;
}
@ToJson
public Integer toJson(CustomType value) {
return value != null ? value.type : 0;
}
}
至此已经完成Type的转换,接下来我们再以title举个例子,别的基本上都是照葫芦画瓢,没什么难度
StringDecode
TitleAdapter
public class TitleAdapter {
@FromJson
public String fromJson(String value) {
byte[] decode = Base64.getDecoder().decode(value);
return new String(decode);
}
@ToJson
public String toJson(String value) {
return new String(Base64.getEncoder().encode(value.getBytes()));
}
}
Int->Boolean
BooleanAdapter
public class BooleanAdapter {
@FromJson
public Boolean fromJson(int value) {
return value == 1;
}
@ToJson
public Integer toJson(Boolean value) {
return value ? 1 : 0;
}
}
Adapter测试
下面我们来测试一下
String json = “{\n” + ““type”: 2,\n” + ““isGood”: 1,\n”
- ““title”: “TW9zaGkgaXMgZmxleGlibGU=”\n”+ “}”;
Moshi moshi = new Moshi.Builder()
.add(new TypeAdapter())
.add(new TitleAdapter())
.add(new BooleanAdapter())
.build();
JsonAdapter jsonAdapter = moshi.adapter(ConfigBean.class);
ConfigBean cofig = jsonAdapter.fromJson(json);
System.out.println(“=========Deserialize ========”);
System.out.println(cofig);
String cofigJson = jsonAdapter.toJson(cofig);
System.out.println(“=========serialize ========”);
System.out.println(cofigJson);
打印Log
=========Deserialize ========
ConfigBean{type=CustomType{type=2, content=‘NORMAL’}, isGood=true, title=‘Moshi is flexible’}
=========serialize ========
{“isGood”:1,“title”:“TW9zaGkgaXMgZmxleGlibGU=”,“type”:2}
符合我们预期的结果,并且我们在开发的时候,只需要将Moshi设置成单例的,一次性将所有的Adapter全部add进去,就可以一劳永逸,然后愉快地进行开发了。
源码解析
Moshi底层采用了Okio进行优化,但是上层的JsonReader,JsonWriter等代码是直接从Gson借鉴过来的,所以不再过多分析,主要是就Moshi的两大特性JsonAdapter以及Kotlin的Codegen解析重点分析一下。
Builder
Moshi moshi = new Moshi.Builder().add(new BooleanAdapter()).build();
Moshi是通过Builder模式进行构建的,支持添加多个JsonAdapter,下面先看看Builder源码
public static final class