Is possible to use setters when Gson deserializes a JSON?

后端 未结 2 2079
渐次进展
渐次进展 2021-01-04 13:17

Is there any way the set methods of a given class, are used when using Gson\'s fromJson method?

I would like to do this because for every String

2条回答
  •  误落风尘
    2021-01-04 13:51

    No, there is not. Gson works mainly by reflection on instance fields. So if you do not plan to move to Jackson that has this feature I think you cannot have a general way to call your setters. So there's no annotation for that.

    BUT

    to achieve your specific need you could:

    1. write your own custom TypeAdapter or
    2. create a constructor that has the string you intend to trim and create a custom InstanceCreator or
    3. parse your JSON as JsonObject, do some processing of the strings and then use that object as source for parsing into your class.

    I can provide you with more hints as long as you post some code or give information about your data/JSON.

提交回复
热议问题