gson 处理null

1.定义null处理类

 1 class StringConverter : JsonSerializer<String?>,
 2     JsonDeserializer<String?> {
 3     override fun serialize(
 4         src: String?, typeOfSrc: Type?,
 5         context: JsonSerializationContext?
 6     ): JsonElement {
 7         return if (src == null) {
 8             JsonPrimitive("")
 9         } else {
10             JsonPrimitive(src.toString())
11         }
12     }
13 
14     @Throws(JsonParseException::class)
15     override fun deserialize(
16         json: JsonElement, typeOfT: Type?,
17         context: JsonDeserializationContext?
18     ): String {
19         return json.asJsonPrimitive.asString
20     }
21 }

 

2.修改构造gson方式 

 1     fun parseDevices(array : JsonArray){
 2         val gson = GsonBuilder().run {
 3             registerTypeAdapter(String::class.java, StringConverter())
 4             create()
 5         }
 6         for (je in array){
 7             val obj = je.asJsonObject
 8             if(!obj.has("type")) continue
 9             val type = obj.get("type").asInt
10             when(type){
11                 1 -> {
12                     val ward = gson.fromJson(je,Wardship::class.java)
13                     ...
14                 }
15 
16                 //...
17             }
18         }
19     }

 

posted @ 2015-07-06 17:34  f9q  阅读(655)  评论(0编辑  收藏  举报