简体   繁体   English

使用GSON反序列化时如何记录丢弃的字段?

[英]How can I log discarded fields when deserializing with GSON?

I am using JSON as a save format. 我正在使用JSON作为保存格式。

If I change the field names of my object GSON will silently discard the original fields upon loading the older version, because they no longer match the new names. 如果更改对象的字段名称,GSON将在加载旧版本时静默丢弃原始字段,因为它们不再与新名称匹配。

I would like to be able to get some notification if I do this accidentally through refactoring, ie "Warning: variableName not found in ObjectType during deserialization." 如果我通过重构意外执行此操作,我希望能够得到一些通知,即“警告:反序列化期间在ObjectType中找不到变量名”。 There is a @Version annotation but it isn't exactly what I'm looking for. 有一个@Version批注,但这并不是我想要的。

Has anyone written a custom deserializer or custom type converter that will throw an error when a field in the JSON does not exist in the type? 是否有人编写了一个自定义反序列化器或自定义类型转换器,当JSON中的字段不存在时会抛出错误? Is there another serialization library that does this? 是否有另一个序列化库可以做到这一点?

Edit: I would still be interested in a GSON deserializer that does this as well, if anyone has one. 编辑:如果有人有一个GSON解串器,我也会对此同样感兴趣。

Jackson can be used to fail on unexpected JSON elements. 杰克逊可用于在意外的JSON元素上失败。 Jackson can also be configured to gather (and log) all unbound JSON elements, as described at http://www.cowtowncoder.com/blog/archives/2010/09/entry_414.html (search for "any setter"). http://www.cowtowncoder.com/blog/archives/2010/09/entry_414.html所述,还可以将Jackson配置为收集(并记录)所有未绑定的JSON元素(搜索“任何设置器”)。

If you're already familiar with Gson, I documented how to use Jackson to do the same things covered in the Gson User Guide at http://programmerbruce.blogspot.com/2011/07/gson-v-jackson-part-6.html . 如果您已经熟悉Gson,我在http://programmerbruce.blogspot.com/2011/07/gson-v-jackson-part-6上记录了如何使用Jackson进行《 Gson用户指南》中介绍的相同操作。 .html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM