反序列化对象时,Gson会忽略null [英] Gson ignore null when deserializing object
本文介绍了反序列化对象时,Gson会忽略null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想反序列化Java中包含空值的json字符串.我想将该对象反序列化为Properties
对象. json字符串类似于:
I want to deserialize a json string that containts a null value in Java. I want to deserialize the object to a Properties
object. The json string is something like:
{"prop1":null, "propr2":"fancy value"}
当我反序列化使用时
String json = //
new Gson().fromJson(json, Properties.class);
由于进入Properties
对象的Hastable
,我得到了空指针异常.如何指示Gson忽略空值的反序列化?
I get a null pointer exception because of the Hastable
that into the Properties
object. How can I instruct Gson to ignore deserialization of null values?
推荐答案
我们有以下解决方案:
1.您所有的数据类都需要扩展抽象类
abstract class PoJoClass
2.创建此安全的反序列化器以从JSON中删除空值
class SafeDeserializer<T : PoJoClass>(private val gson: Gson) :JsonDeserializer<T> {
override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?): T {
val jsonObject = json as JsonObject
removeNullsFromJson(jsonObject)
return gson.fromJson(jsonObject, typeOfT)
}
private fun removeNullsFromJson(jsonObject: JsonObject) {
val iterator = jsonObject.keySet().iterator()
while (iterator.hasNext()) {
val key = iterator.next()
when(val json = jsonObject[key]){
is JsonObject -> removeNullsFromJson(json)
is JsonNull -> iterator.remove()
}
}
}
}
3.并将其注册到您的GSON实例中
val gson = Gson().newBuilder()
.registerTypeHierarchyAdapter(PoJoClass::class.java, SafeDeserializer<PoJoClass>(Gson()))
.create()
这篇关于反序列化对象时,Gson会忽略null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文