有没有办法配置gson来忽略未知的枚举值?对于 示例
在我的客户端代码中有一个枚举DeviceType有2个枚举值:PC, MOBILE
但是当服务器被发送另一种类型,例如MAC作为另一种类型 设备类型。如何配置我的gson deserilalizer来设置 DeviceType = null而不是抛出异常?
谢谢,
肖恩
答案 0 :(得分:2)
您可以轻松编写忽略未知值的自定义JsonDeserializer
。阅读更多here。
有关起点,请查看源gson源代码,类com.google.gson.DefaultTypeAdapters.EnumTypeAdapter
答案 1 :(得分:1)
现在我们可以使用可为空的枚举类型,例如:
data class SomeDTO (
val type : DeviceType?,
//other values
)
在这种情况下,解析不会有任何异常。
答案 2 :(得分:0)
我不能100%确定这是否可行,但您可以在枚举上声明一个lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "CoreTest3")
let description = NSPersistentStoreDescription()
description.shouldInferMappingModelAutomatically = true
description.shouldMigrateStoreAutomatically = true
container.persistentStoreDescriptions = [description]
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
方法来覆盖默认实现,其中一个为未知值而不是IllegalArgumentException返回null。
documentation建议使用重写的静态实现。
然后它只取决于Gson如何处理该方法的结果(假设Gson甚至使用该方法进行解析),但它是一个简单的解决方法,值得一试。