Android如何解析异构列表
作者:benio
前言
开发业务需求时,遇到了列表中包含完全不同类型的数据结构。这种列表我们称为异构列表。以聊天记录列表为例
[ { "msgType" : "text", "id" : "1", "content" : "Hello world" }, { "msgType" : "record", "id" : "2", "url" : "https://xxxx.mp4", "length" : 123450 }, { "msgType" : "image", "id" : "3", "url" : "https://xxxx.jpg", "size" : "300x300" } ]
要想解析上面的JSON,手动解析不是不行,但肯定不推荐。如果直接使用解析工具,比如用Gson来解析的话,无论定义什么样的数据结构好像都不符合上面的列表元素。
那可不可以做到,我们告诉Gson列表中各个元素分别是什么样的数据类型,这样它不就知道该怎么解析了吗?接下来我们通过Gson的TypeAdapter来实现自定义解析。
实现方案
先定义好各种数据类型,与msgType字段一一对应
abstract class BaseMessage(val id: String?, val msgType: String?) class TextMessage(id: String?, msgType: String?, val content: String? ) : BaseMessage(id, msgType) class ImageMessage(id: String?, msgType: String?, val url: String?, val size: String? ) : BaseMessage(id, msgType) class RecordMessage(id: String?, msgType: String?, val url: String?, val length: Long ) : BaseMessage(id, msgType)
接着自定义一个TypeAdapter。
class BaseMessageTypeAdapter : TypeAdapter<BaseMessage>() { override fun write(out: JsonWriter, value: BaseMessage?) { } override fun read(`in`: JsonReader): BaseMessage? { } }
可以看到里面有两个方法:write()负责序列化,read()负责反序列化。我们先重点关注read()的实现
实现read()的基本思路如下
- 读取msgType字段
- 根据msgType判断对应的数据类型
- 根据该数据类型获取解析该类型的TypeAdapter
- 交给对应类型的TypeAdapter解析
依照上述思路,可以写出read()的基本实现代码。当然这是比较粗糙的实现,实际上还有其他情况要考虑
class BaseMessageTypeAdapter(private val gson: Gson, private val skipPast: TypeAdapterFactory ) : TypeAdapter<BaseMessage>() { override fun read(`in`: JsonReader): BaseMessage? { // 1.读取msgType字段 val jsonObject = Streams.parse(`in`).asJsonObject val msgType = jsonObject.get("msgType")?.asString // 2.根据msgType获取解析该类型的TypeAdapter val adapter = getTypeAdapterByType(msgType) // 3.交给对应类型的TypeAdapter解析 return adapter?.fromJsonTree(jsonObject) } }
write()方法没什么好说的,直接交给对应类型的TypeAdapter序列化
class BaseMessageTypeAdapter(private val gson: Gson, private val skipPast: TypeAdapterFactory ) : TypeAdapter<BaseMessage>() { override fun write(out: JsonWriter, value: BaseMessage?) { if (value == null) { out.nullValue() return } getTypeAdapterByType(value.msgType)?.write(out, value) } }
接着就是实现getTypeAdapterByType()方法。
private fun getTypeAdapterByType(type: String?): TypeAdapter<BaseMessage>? { return when (type) { "text" -> getTypeAdapter(TextMessage::class.java) "image" -> getTypeAdapter(ImageMessage::class.java) "record" -> getTypeAdapter(RecordMessage::class.java) else -> null } } private fun <R : BaseMessage> getTypeAdapter(clazz: Class<R>): TypeAdapter<BaseMessage> { // 获取Gson中该类型对应的TypeAdapter return SubTypeAdapterWrapper(clazz, gson.getDelegateAdapter(skipPast, TypeToken.get(clazz))) }
逻辑也比较简单。需要注意的是,在getTypeAdapter()方法中,要将TypeAdapter<out BaseMessage>转换成TypeAdapter<BaseMessage>。接下来我们看看SubTypeAdapterWrapper是怎样实现的
class SubTypeAdapterWrapper<T, R : T>(private val clazz: Class<R>, private val adapter: TypeAdapter<R> ) : TypeAdapter<T>() { override fun write(out: JsonWriter, value: T) { if (!clazz.isInstance(value)) { throw JsonSyntaxException("Expected a " + clazz.name + " but was " + value) } adapter.write(out, value as R) } override fun read(`in`: JsonReader): T { return adapter.read(`in`) } }
其实就是一个包装类。将解析R类型的TypeAdapter包装成解析T类型的TypeAdapter。
最后就是实现一个TypeAdapterFactory,并将其注册到Gson
class BaseMessageTypeAdapterFactory : TypeAdapterFactory { override fun <T : Any?> create(gson: Gson, type: TypeToken<T>): TypeAdapter<T>? { if (!BaseMessage::class.java.isAssignableFrom(type.rawType)) { return null } return BaseMessageTypeAdapter(gson, this) as (TypeAdapter<T>) } }
写个测试用例测试一下
抽象封装
为了更好的复用,接下来我们要对BaseMessageTypeAdapter改造一下。
定义一个新的TypeAdapter子类。将类型和TypeAdapter的关系用Map来存储,并提供方法给外部调用。
public class HeterogeneousTypeAdapter<T> extends TypeAdapter<T> { private final Gson mGson; private final TypeAdapterFactory mSkipPast; private final String mFieldName; private final Map<String, TypeAdapter<T>> mClassToAdapterMap = new HashMap<>(); private final Map<String, TypeAdapter<T>> mFieldToAdapterMap = new HashMap<>(); public HeterogeneousTypeAdapter(Gson gson, TypeAdapterFactory skipPast, String fieldName) { mGson = gson; mSkipPast = skipPast; mFieldName = fieldName; } public <R extends T> void addSubTypeAdapter(final String fieldValue, final Class<R> cls) { final TypeAdapter<R> typeAdapter = mGson.getDelegateAdapter(mSkipPast, TypeToken.get(cls)); addSubTypeAdapter(fieldValue, cls, typeAdapter); } public <R extends T> void addSubTypeAdapter(final String fieldValue, final Class<R> cls, final TypeAdapter<R> typeAdapter) { final TypeAdapter<T> adapter = new SubTypeAdapterWrapper<>(cls, typeAdapter); mClassToAdapterMap.put(cls.getName(), adapter); mFieldToAdapterMap.put(fieldValue, adapter); } @Override public void write(JsonWriter out, T value) throws IOException { if (value == null) { out.nullValue(); return; } getTypeAdapterByClass(value.getClass()).write(out, value); } @Override public T read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } final JsonObject jsonObject = Streams.parse(in).getAsJsonObject(); final JsonElement fieldElement = jsonObject.get(mFieldName); if (fieldElement == null || fieldElement.isJsonNull()) { throw new JsonSyntaxException("Field " + mFieldName + " is null or not found"); } final String field = fieldElement.getAsJsonPrimitive().getAsString(); final TypeAdapter<T> adapter = getTypeAdapterByField(field); if (adapter == null) { // Unknown field, just skip return null; } return adapter.fromJsonTree(jsonObject); } private TypeAdapter<T> getTypeAdapterByClass(Class<?> cls) { TypeAdapter<T> adapter = mClassToAdapterMap.get(cls.getName()); if (adapter == null) { throw new JsonParseException("Unknown class : " + cls); } return adapter; } private TypeAdapter<T> getTypeAdapterByField(String field) { return mFieldToAdapterMap.get(field); } }
使用方式
class BaseMessageTypeAdapterFactory : TypeAdapterFactory { override fun <T : Any?> create(gson: Gson, type: TypeToken<T>): TypeAdapter<T>? { if (!BaseMessage::class.java.isAssignableFrom(type.rawType)) { return null } val adapter = HeterogeneousTypeAdapter<BaseMessage>(gson, this, "msgType") // 注册各种类型 adapter.addSubTypeAdapter("text", TextMessage::class.java) adapter.addSubTypeAdapter("image", ImageMessage::class.java) adapter.addSubTypeAdapter("record", RecordMessage::class.java) return adapter as (TypeAdapter<T>) } }
总结
通过自定义TypeAdapter,我们实现了解析异构列表的功能。免除手动解析的繁琐工作,避免出现不必要的错误。
以上就是Android如何解析异构列表的详细内容,更多关于Android 解析异构列表的资料请关注脚本之家其它相关文章!