Genson de/serialization of private fileds

23 views
Skip to first unread message

Michal Stehlik

unread,
Oct 7, 2014, 6:42:26 AM10/7/14
to gen...@googlegroups.com
Hi Eugen,

I have eg. class like this

public class ImmutableClass {
    private int myValue;

    public int getMyValue() {
        return myValue;
    }
}

I want to set this private property directly via deserializing of json. How is this possible?
I use GensonBuilder.useFields(true).

Eugen Cepoi

unread,
Oct 7, 2014, 7:30:17 AM10/7/14
to gen...@googlegroups.com
Hi Michal,

Try GensonBuilder.useFields(true, VisibilityFilter.PRIVATE), this will include also private/protected fields. If you want to use only fields you can via .useMethods(false).

Note that you can also have a constructor that takes as argument all your properties (the names should match with the ones in the json) and sets them. If you make the properties final you could even make them  public. You can then tell to Genson to work with them via builder.useConstructorWithArguments(true). If you have multiple constructors then mark with @JsonCreator the one you want Genson to use. This is the way usually to achieve immutable structures.

--
You received this message because you are subscribed to the Google Groups "Genson user group" group.
To unsubscribe from this group and stop receiving emails from it, send an email to genson+un...@googlegroups.com.
To post to this group, send email to gen...@googlegroups.com.
Visit this group at http://groups.google.com/group/genson.
To view this discussion on the web visit https://groups.google.com/d/msgid/genson/bdf24d22-92bf-443e-ab4d-9fb804a7f590%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Michal Stehlik

unread,
Oct 8, 2014, 1:59:09 PM10/8/14
to gen...@googlegroups.com
Thank you a lot, this helps. Is it also possible combine visibilities eg.: GensonBuilder.useFields(true, VisibilityFilter.PRIVATE | VisibilityFilter.PROTECTED) ?

Eugen Cepoi

unread,
Oct 8, 2014, 2:07:41 PM10/8/14
to gen...@googlegroups.com
Yep you can (but not exactly this way), have a look at the implementation of VisibilityFilter https://github.com/owlike/genson/blob/master/genson/src/main/java/com/owlike/genson/reflect/VisibilityFilter.java.

Note that the visibilityfilter defines what modifiers should be excluded, for example the private one is:

new
VisibilityFilter(Modifier.TRANSIENT, Modifier.NATIVE, Modifier.STATIC)

adding Modifier.PRIVATE would forbid private but allows protected, public etc.



Reply all
Reply to author
Forward
0 new messages