Gson 数据解析
0x01 Kotlin Gson 解析 data class 两条黄金法则:
1、 String 必须是可空类型 String?
2、 需要使用默认值,则全部字段都必须给予默认值,以满足kotlin对象有空的构造函数
0x02 手动解析Gson基础字段
1、msg 可空String解析 jsonReader.peek() == JsonToken.NULL
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| import com.google.gson.Gson import com.google.gson.JsonSyntaxException import com.google.gson.TypeAdapter import com.google.gson.reflect.TypeToken import com.google.gson.stream.JsonReader import com.google.gson.stream.JsonToken import okhttp3.ResponseBody import retrofit2.Converter import java.lang.reflect.ParameterizedType import java.lang.reflect.Type
class ResponseBodyConverter(val gson: Gson, val type: Type) : Converter<ResponseBody, BaseResponse<Any>> { override fun convert(value: ResponseBody): BaseResponse<Any> { val dataType = GenericsUtils.getParameterUpperBound( 0, type as ParameterizedType ) val baseResponse = BaseResponse<Any>() val jsonReader = JsonReader(value.charStream()) try { jsonReader.beginObject() while (jsonReader.hasNext()) { val name: String = jsonReader.nextName() when (name) { "code" -> { baseResponse.code = jsonReader.nextString() } "msg" -> { if (jsonReader.peek() == JsonToken.NULL) { jsonReader.nextNull() baseResponse.msg = null } else { baseResponse.msg = jsonReader.nextString() } } "data" -> { val mapped: TypeAdapter<*>? = gson.getAdapter(TypeToken.get(dataType)) baseResponse.data = mapped?.read(jsonReader) } else -> { jsonReader.skipValue() } } } } catch (e: IllegalStateException) { throw JsonSyntaxException(e) } catch (e: IllegalAccessException) { throw AssertionError(e) } jsonReader.endObject() return baseResponse } }
|