Class GensonBuilder

  • Direct Known Subclasses:
    Genson.Builder

    public class GensonBuilder
    extends Object
    Use the GensonBuilder class when you want to create a custom Genson instance. This class allows you for example to register custom converters/serializers/deserializers withConverters(Converter...) or custom converter Factories withConverterFactory(Factory).

    This class combines the GensonBuilder design pattern with template pattern providing handy configuration and extensibility. All its public methods are intended to be used in the GensonBuilder "style" and its protected methods are part of the template. When you call create() method, it will start assembling all the configuration and build all the required components by using the protected methods. For example if you wish to use in your projects a GensonBuilder that will always create some custom BeanDescriptorProvider you have to extend createBeanDescriptorProvider(), or imagine that you implemented some Converters that you always want to register then override getDefaultConverters().

    Author:
    Eugen Cepoi
    • Constructor Detail

      • GensonBuilder

        public GensonBuilder()
    • Method Detail

      • setDefaultType

        public GensonBuilder setDefaultType​(ValueType type,
                                            Class<?> clazz)
        Set the class to use for deserialization of the specified ValueType when the Java type cannot be determined based on static type information or JSON metadata.
        Parameters:
        type - the ValueType to set the default class for
        clazz - the default class for the specified ValueType
        Returns:
        a reference to this builder
      • addAlias

        public GensonBuilder addAlias​(String alias,
                                      Class<?> forClass)
        Alias used in serialized class metadata instead of the full class name. See ClassMetadataConverter for more metadata. If you add an alias, it will automatically enable the class metadata feature, as if you used useClassMetadata(boolean).
        Parameters:
        alias -
        forClass -
        Returns:
        a reference to this builder.
      • addPackageAlias

        public GensonBuilder addPackageAlias​(String alias,
                                             String forPackage)
        Similar to addAlias(String, Class), this allows creating an alias for all serialized classes within a package. When a class is present within the specified package, instead of the full class name being serialized, it will generate the following String: alias + '.' + className
        Parameters:
        alias - alias for classes within a specific package. The provided value must not contain a period (.)
        forPackage - the package to which the alias will be applied
        Returns:
        a reference to this builder
        Throws:
        IllegalArgumentException - if alias contains a period
        Since:
        2.0
        See Also:
        addAlias(String, Class)
      • withConverters

        public GensonBuilder withConverters​(Converter<?>... converter)
        Registers converters mapping them to their corresponding parameterized type.
        Parameters:
        converter -
        Returns:
        a reference to this builder.
      • withConverter

        public <T> GensonBuilder withConverter​(Converter<T> converter,
                                               Class<? extends T> type)
        Register converter by mapping it to type argument.
        Parameters:
        converter - to register
        type - of objects this converter handles
        Returns:
        a reference to this builder.
      • withConverter

        public <T> GensonBuilder withConverter​(Converter<T> converter,
                                               GenericType<? extends T> type)
        Register converter by mapping it to the parameterized type of type argument.
        Parameters:
        converter - to register
        type - of objects this converter handles
        Returns:
        a reference to this builder.
      • withConverterFactory

        public GensonBuilder withConverterFactory​(Factory<? extends Converter<?>> factory)
        Registers converter factories.
        Parameters:
        factory - to register
        Returns:
        a reference to this builder.
      • withSerializerFactory

        public GensonBuilder withSerializerFactory​(Factory<? extends Serializer<?>> factory)
        Registers serializer factories.
        Parameters:
        factory - to register
        Returns:
        a reference to this builder.
      • withDeserializerFactory

        public GensonBuilder withDeserializerFactory​(Factory<? extends Deserializer<?>> factory)
        Registers deserializer factories.
        Parameters:
        factory - to register
        Returns:
        a reference to this builder.
      • withContextualFactory

        public GensonBuilder withContextualFactory​(ContextualFactory<?>... factories)
        ContextualFactory is actually in a beta status, it will not be removed, but might be refactored.
      • withConverterFactory

        public GensonBuilder withConverterFactory​(ChainedFactory chainedFactory)
        A ChainedFactory provides a way to use custom Converters that have access to the default Converters. An example of use is to wrap incoming/outgoing json in a root object and delegate then the ser/de to the default Converter. This mechanism is internally used by Genson to decorate the different Converters with additional behaviour (null handling, ser/de of polymorphic types with class info, runtime type based ser/de, etc). Note that you can't use it in situations where you want to start reading/writing some partial infos and want to delegate the rest to the default Converter.
      • withBeanPropertyFactory

        public GensonBuilder withBeanPropertyFactory​(BeanPropertyFactory... factories)
        Allows you to register new BeanPropertyFactory responsible of creating BeanProperty accessors, mutators and BeanCreators. This is a very low level feature, you probably don't need it.
      • withBundle

        public GensonBuilder withBundle​(GensonBundle... bundles)
        Register some genson bundles. For example to enable JAXB support:

         builder.withBundle(new JAXBExtension());
         
        All bundles should be registered before any other customization.
        See Also:
        GensonBundle
      • withClassLoader

        public GensonBuilder withClassLoader​(ClassLoader loader)
        Override the default classloader
        Parameters:
        loader - classloader which will be used to load classes while deserializing
        Returns:
        a reference to this builder
      • with

        public GensonBuilder with​(BeanMutatorAccessorResolver... resolvers)
        Register additional BeanMutatorAccessorResolver that will be used before the standard ones.
        Parameters:
        resolvers -
        Returns:
        a reference to this builder.
      • with

        public GensonBuilder with​(PropertyNameResolver... resolvers)
        Registers the specified resolvers in the order they were defined and before the standard ones.
        Parameters:
        resolvers -
        Returns:
        a reference to this builder.
      • rename

        public GensonBuilder rename​(Class<?> fieldOfType,
                                    String toName)
        Renames all fields of type fieldOfType to toName.
      • rename

        public GensonBuilder rename​(String field,
                                    Class<?> fromClass,
                                    String toName)
        Renames all fields named field declared in class fromClass to toName.
      • rename

        public GensonBuilder rename​(String field,
                                    String toName,
                                    Class<?> fieldOfType)
        Renames all fields named field and of type fieldOfType to toName.
      • rename

        public GensonBuilder rename​(String field,
                                    Class<?> fromClass,
                                    String toName,
                                    Class<?> ofType)
        Renames all fields named field, of type fieldOfType and declared in fromClass to toName.
      • setSkipNull

        public GensonBuilder setSkipNull​(boolean skipNull)
        If true will not serialize null values
        Parameters:
        skipNull - indicates whether null values should be serialized or not.
        Returns:
        a reference to this builder.
      • isSkipNull

        public boolean isSkipNull()
      • setHtmlSafe

        public GensonBuilder setHtmlSafe​(boolean htmlSafe)
        If true \,<,>,&,= characters will be replaced by ', <, >, &, =
        Parameters:
        htmlSafe - indicates whether serialized data should be html safe.
        Returns:
        a reference to this builder.
      • isHtmlSafe

        public boolean isHtmlSafe()
      • useClassMetadata

        public GensonBuilder useClassMetadata​(boolean enabled)
        Indicates whether class metadata should be serialized and used during deserialization.
        See Also:
        ClassMetadataConverter
      • useDateFormat

        public GensonBuilder useDateFormat​(DateFormat dateFormat)
        Specifies the data format that should be used for java.util.Date serialization and deserialization.
        Parameters:
        dateFormat -
        Returns:
        a reference to this builder.
      • isThrowExceptionOnNoDebugInfo

        public boolean isThrowExceptionOnNoDebugInfo()
      • useMethods

        public GensonBuilder useMethods​(boolean enabled)
        If true, getters and setters would be used during serialization/deserialization in favor of fields. If there is not getter/setter for a field then the field will be used, except if you specified that fields should not be used with useFields(boolean). By default getters, setters and fields will be used.
      • useFields

        public GensonBuilder useFields​(boolean enabled)
        If true, fields will be used when no getter/setter is available, except if you specified that no getter/setter should be used with useMethods(boolean), in that case only fields will be used. By default getters, setters and fields will be used.
      • useBeanViews

        public GensonBuilder useBeanViews​(boolean enabled)
        If true BeanView mechanism will be enabled.
      • useRuntimeType

        public GensonBuilder useRuntimeType​(boolean enabled)
        If true the concrete type of the serialized object will always be used. So if you have List type it will not use the Number serializer but the one for the concrete type of the current value.
        Parameters:
        enabled -
        Returns:
        a reference to this builder.
      • useConstructorWithArguments

        public GensonBuilder useConstructorWithArguments​(boolean enabled)
        If true constructor and method arguments name will be resolved from the generated debug symbols during compilation. It is a very powerful feature from Genson, you should have a look at ASMCreatorParameterNameResolver.
        Parameters:
        enabled -
        Returns:
        a reference to this builder.
        See Also:
        setThrowExceptionIfNoDebugInfo(boolean)
      • useStrictDoubleParse

        public GensonBuilder useStrictDoubleParse​(boolean strictDoubleParse)
      • useIndentation

        public GensonBuilder useIndentation​(boolean indent)
        If true outputed json will be indented using two spaces, otherwise (by default) all is printed on same line.
      • useDateAsTimestamp

        public GensonBuilder useDateAsTimestamp​(boolean enabled)
      • useMetadata

        public GensonBuilder useMetadata​(boolean metadata)
      • useByteAsInt

        public GensonBuilder useByteAsInt​(boolean enable)
      • failOnMissingProperty

        public GensonBuilder failOnMissingProperty​(boolean enable)
        If set to true, Genson will throw a JsonBindingException when it encounters a property in the incoming json that does not match a property in the class. False by default.
        Parameters:
        enable -
        Returns:
      • useClassMetadataWithStaticType

        public GensonBuilder useClassMetadataWithStaticType​(boolean enable)
        If set to false, during serialization class metadata will be serialized only for types where the runtime type differs from the static one. Ex:
         class Person {
           public Address address;
         }
         
        Here if the concrete instance of address is Address then this type will not be serialized as metadata, but if they differ then it is serialized. By default this option is true, all types are serialized.
        Parameters:
        enable -
        Returns:
      • acceptSingleValueAsList

        public GensonBuilder acceptSingleValueAsList​(boolean enable)
        Wrap a single value into a list when a list is expected. Useful when dealing with APIs that unwrap arrays containing a single value. Disabled by default.
      • useDefaultValue

        public GensonBuilder useDefaultValue​(Object value,
                                             Class<?> targetType)
        Uses the passed value as the default value for this type.
      • wrapRootValues

        public GensonBuilder wrapRootValues​(String inputKey,
                                            String outputKey)
        Will wrap all the root objects under outputKey during serializaiton and unwrap the content under inputKey during deserializaiton. For example: Genson genson = new GensonBuilder().wrapRootValues("request", "response").create(); // would produce: {"response": {... person properties ...}} genson.serialize(person); Person p = genson.deserialize("{\"request\":{...}}", Person.class); If you need this mechanism only for some types or using different root keys, then you can register JaxbBundle with wrapRootValues(true) and annotate the specific classes with XmlRootElement.
      • failOnNullPrimitive

        public GensonBuilder failOnNullPrimitive​(boolean enabled)
        False by default. When enabled a JsonBindingException will be thrown if null is encountered during serialization (should never happen) or deserialization for a primitive type.
      • create

        public Genson create()
        Creates an instance of Genson. You may use this method as many times you want. It wont change the state of the builder, in sense that the returned instance will have always the same configuration.
        Returns:
        a new instance of Genson built for the current configuration.
      • create

        protected Genson create​(Factory<Converter<?>> converterFactory,
                                Map<String,​Class<?>> classAliases,
                                Map<String,​String> packageAliases)
        In theory this allows you to extend Genson class and to instantiate it, but actually you can not do it as Genson class is final. If some uses cases are discovered it may change.
        Parameters:
        converterFactory -
        classAliases -
        Returns:
        a new Genson instance.
      • createConverterFactory

        protected Factory<Converter<?>> createConverterFactory()
        You should override this method if you want to add custom ChainedFactory or if you need to chain them differently.
        Returns:
        the converter factory instance that will be used to resolve ALL converters.
      • getDefaultConverters

        protected List<Converter<?>> getDefaultConverters()
        You can override this methods if you want to change the default converters (remove some, change the order, etc).
        Returns:
        the default converters list, must be not null.
      • addDefaultConverterFactories

        protected void addDefaultConverterFactories​(List<Factory<? extends Converter<?>>> factories)
        Override this method if you want to change the default converter factories.
        Parameters:
        factories - list, is not null.
      • addDefaultContextualFactories

        protected void addDefaultContextualFactories​(List<ContextualFactory<?>> factories)
      • getDefaultSerializers

        protected List<Serializer<?>> getDefaultSerializers()
      • addDefaultSerializerFactories

        protected void addDefaultSerializerFactories​(List<Factory<? extends Serializer<?>>> serializerFactories)
      • getDefaultDeserializers

        protected List<Deserializer<?>> getDefaultDeserializers()
      • addDefaultDeserializerFactories

        protected void addDefaultDeserializerFactories​(List<Factory<? extends Deserializer<?>>> deserializerFactories)
      • createBeanDescriptorProvider

        protected BeanDescriptorProvider createBeanDescriptorProvider()
        Creates the standard BeanDescriptorProvider that will be used to provide BeanDescriptor instances for serialization/deserialization of all types that couldn't be handled by standard and custom converters and converter factories.
        Returns:
        the BeanDescriptorProvider instance.
      • getFactories

        public final List<Factory<?>> getFactories()
      • isDateAsTimestamp

        public final boolean isDateAsTimestamp()