简体   繁体   中英

Custom serialize and deserialize to create JSON

I have a class with 2 values: val1 and val2. I am sending val1 to register (create) API and val2 is auto filled by API itself. I do not want to send val2 while calling create API and that API is not designed for handling unwanted values.

In short I want to ignore val2 while I call create API but I want it while I call get API.

The code that I have right now creates JSON including both the values assigning null to val2. This causes that API to throw an exception.

Is there any easy way of doing it (java /groovy)?

Is there any easy way of doing it (java /groovy)?

Not 100% sure I'm understanding your need. I believe it depends on what json de/serializer you are using. For example, using Jackson we do:

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonTypeName("account")
public class Account {

I believe this allows us to load in objects with a ton of extra json fields into objects without corresponding java fields. To quote from the javadocs :

Property that defines whether it is ok to just ignore any unrecognized properties during deserialization. If true, all properties that are unrecognized -- that is, there are no setters or creators that accept them -- are ignored without warnings (although handlers for unknown properties, if any, will still be called) without exception.

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