|
1 | 1 | package com.gomsang.lab.publicmask.libs.http.mask
|
2 | 2 |
|
3 | 3 | import com.gomsang.lab.publicmask.libs.constants.WebAddresses
|
4 |
| -import com.gomsang.lab.publicmask.libs.http.kakao.KakaoAPI |
| 4 | +import com.google.gson.Gson |
| 5 | +import com.google.gson.GsonBuilder |
| 6 | +import com.google.gson.TypeAdapter |
| 7 | +import com.google.gson.TypeAdapterFactory |
| 8 | +import com.google.gson.reflect.TypeToken |
| 9 | +import com.google.gson.stream.JsonReader |
| 10 | +import com.google.gson.stream.JsonToken |
| 11 | +import com.google.gson.stream.JsonWriter |
5 | 12 | import retrofit2.Retrofit
|
6 | 13 | import retrofit2.converter.gson.GsonConverterFactory
|
| 14 | +import java.io.IOException |
| 15 | + |
7 | 16 |
|
8 | 17 | class Mask {
|
9 | 18 | val api: MaskAPI
|
10 | 19 |
|
11 | 20 | constructor() {
|
| 21 | + |
| 22 | + class StringAdapter : TypeAdapter<String?>() { |
| 23 | + @Throws(IOException::class) |
| 24 | + override fun read(reader: JsonReader): String { |
| 25 | + if (reader.peek() === JsonToken.NULL) { |
| 26 | + reader.nextNull() |
| 27 | + return "" |
| 28 | + } |
| 29 | + return reader.nextString() |
| 30 | + } |
| 31 | + |
| 32 | + @Throws(IOException::class) |
| 33 | + override fun write(writer: JsonWriter, value: String?) { |
| 34 | + if (value == null) { |
| 35 | + writer.nullValue() |
| 36 | + return |
| 37 | + } |
| 38 | + writer.value(value) |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + |
| 43 | + class NullStringToEmptyAdapterFactory<T> : TypeAdapterFactory { |
| 44 | + override fun <T> create(gson: Gson, type: TypeToken<T>): TypeAdapter<T>? { |
| 45 | + val rawType = type.rawType as Class<T> |
| 46 | + return if (rawType != String::class.java) { |
| 47 | + null |
| 48 | + } else StringAdapter() as TypeAdapter<T> |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + val gson = |
| 53 | + GsonBuilder().registerTypeAdapterFactory(NullStringToEmptyAdapterFactory<Any>()).create() |
| 54 | + |
12 | 55 | val retrofit: Retrofit = Retrofit.Builder()
|
13 | 56 | .baseUrl(WebAddresses.URL_MASK_API)
|
14 |
| - .addConverterFactory(GsonConverterFactory.create()) |
| 57 | + .addConverterFactory(GsonConverterFactory.create(gson)) |
15 | 58 | .build()
|
16 | 59 | api = retrofit.create<MaskAPI>(MaskAPI::class.java)
|
17 | 60 | }
|
|
0 commit comments