简体   繁体   中英

Jackson JSON library: Ignore fields that cause an exception when serializing?

I've got a get_____ method that will throw an exception when it's called wrong. (The code was written by someone else and I'm not going to be able to change this part of the problem)

Is there a way to tell Jackson to try and serialize things, and if an exception occurs to just ignore the field (ie, don't serialize the exception-generating field) and to keep going with the rest of the serialization instead?

I've seen that there's an option to ignore NULL values when serializing, which is great, but I'm looking specifically for ignoring exceptions after calling a get method.

I'd rather not mark individual fields with @JsonIgnore because sometimes the method works on some objects (in which case I'd like to serialize the result of the successful get method) and on some other objects it doesn't (in which case I'd like to skip the get method). Plus, it's labor-intensive and I'd rather have a blanket solution.

EDIT after realizing the topic was about "serialization":

You have to create a custom JsonSerializer .
I suggest you to extend StdSerializer and catch for errors returning null (combining this with the parameter to not write nulls).
Probably you can find inspiration looking at FailingSerializer .

Basically, I think you should just override the serialize method of StdSerializer , calling super.serialize catching all Exception s.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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