google / gson

A Java serialization/deserialization library to convert Java Objects into JSON and back
Apache License 2.0
23.33k stars 4.28k forks source link

Encrypt some annotated fields #1230

Open andrea-bologna opened 6 years ago

andrea-bologna commented 6 years ago

Hello, I have some fields annotated with a custom annotation @MyId. It can be applied to single elements (int, strings...) or collections. My final target is to translate this fields using a custom component (in a web page, I have the key in the session) and I just would like to do this during the JSON serialization.

I cannot find any way to achieve this using GSON (I don't want to write a full custom serializer for each possibile response my backend will send, of course), can you help me?

Thanks Andrea

NightlyNexus commented 6 years ago

I'm not sure that it's best to do this at the serialization layer, but maybe you could add @JsonAdapter(MyTypeAdapterFactory.class) to the fields, where MyTypeAdapterFactory creates TypeAdapters that delegate serialization and do some logic for all types.

There's nothing Gson needs to do to support this, but people on Stack Overflow may have creative solutions if you provide some example code of what you'd like to achieve.

andrea-bologna commented 6 years ago

I've done a lot of search but didn't find anything fitting my needs, this is the reason I wrote a topic here.

I can't annotate with a custom JsonAdapter because it would affect my type everytime (otherwise I should create a sort of "static variables" that the app could change which is not so good) and can't add the factory to the Gson instance just because my annotated types are primitive types such as int or String. So I don't think I would know if the adapted value would be "annotated field of any other object" or a simple other field.

Isn't there anything in Gson to say: please use this adapter for fields with this annotation (like for example we can do to exclude fields with a given annotation)???

Best