Class Genson


  • public final class Genson
    extends Object

    Main class of the library. Instances of Genson are thread safe and should be reused. You can instantiate it multiple times but it is better to have an instance per configuration so you can benefit of better performances.

    For more examples have a look at the online documentation.

    To create a new instance of Genson you can use the default no arg constructor or the GensonBuilder class to have control over Gensons configuration.
    A basic usage of Genson would be:

     Genson genson = new Genson();
     String json = genson.serialize(new int[] { 1, 2, 3 });
     int[] arrayOfInt = genson.deserialize(json, int[].class);
     // (multi-dimensional arrays are also supported)
    
     // genson can also deserialize primitive types without class information
     Number[] arrayOfNumber = genson.deserialize("[1, 2.03, 8877463]", Number[].class);
     // or even
     Object[] arrayOfUnknownTypes = genson
                    .deserialize("[1, false, null, 4.05, \"hey this is a string!\"]", Object[].class);
     // it can also deserialize json objects of unknown types to standard java types such as Map, Array, Long etc.
     Map<String, Object> map = (Map<String, Object>) genson.deserialize("{\"foo\":1232}", Object.class);
     

    Every object serialized with Genson, can be deserialized back into its concrete type! Just enable it via the builder GensonBuilder.useClassMetadata(boolean). You can also deserialize to objects that don't provide a default constructor with no arguments GensonBuilder.useConstructorWithArguments(boolean).

    Author:
    Eugen Cepoi
    • Constructor Detail

      • Genson

        public Genson()
        The default constructor will use the default configuration provided by the GensonBuilder. In most cases using this default constructor will suffice.
      • Genson

        public Genson​(Factory<Converter<?>> converterFactory,
                      BeanDescriptorProvider beanDescProvider,
                      boolean skipNull,
                      boolean htmlSafe,
                      Map<String,​Class<?>> classAliases,
                      Map<String,​String> packageAliases,
                      boolean withClassMetadata,
                      boolean strictDoubleParse,
                      boolean indent,
                      boolean withMetadata,
                      boolean failOnMissingProperty,
                      Map<Class<?>,​Object> defaultValues,
                      DefaultTypes defaultTypes,
                      RuntimePropertyFilter runtimePropertyFilter,
                      UnknownPropertyHandler unknownPropertyHandler,
                      ClassLoader classLoader)
        Instead of using this constructor you should use GensonBuilder.
        Parameters:
        converterFactory - providing instance of converters.
        beanDescProvider - providing instance of BeanDescriptor used during bean serialization and deserialization.
        skipNull - indicates whether null values should be serialized. False by default, null values will be serialized.
        htmlSafe - indicates whether \,<,>,&,= characters should be replaced by their Unicode representation.
        classAliases - association map between classes and their aliases, used if withClassMetadata is true.
        packageAliases - association map between a group of classes in a package and their alias, used if withClassMetadata is true.
        withClassMetadata - indicates whether class name should be serialized and used during deserialization to determine the type. False by default.
        strictDoubleParse - indicates whether to use or not double approximation. If false (by default) it enables Genson custom double parsing algorithm, that is an approximation of Double.parse but is a lot faster. If true, Double.parse method will be usead instead. In most cases you should be fine with Genson algorithm, but if for some reason you need to have 100% match with Double.parse, then enable strict parsing.
        indent - true if outputed json must be indented (pretty printed).
        withMetadata - true if ObjectReader instances must be configured with metadata feature enabled. if withClassMetadata is true withMetadata will be automatically true.
        failOnMissingProperty - throw a JsonBindingException when a key in the json stream does not match a property in the Java Class.
        defaultValues - contains a mapping from the raw class to the default value that should be used when the property is missing.
        defaultValues - contains a mapping from the raw class to the default value that should be used when the property is missing.
        runtimePropertyFilter - is used to define what bean properties should be excluded from ser/de at runtime.
        unknownPropertyHandler - is used to handle unknown properties during ser/de.
    • Method Detail

      • provideConverter

        public <T> Converter<T> provideConverter​(Type forType)
        Provides an instance of Converter capable of handling objects of type forType.
        Parameters:
        forType - the type for which a converter is needed.
        Returns:
        the converter instance.
        Throws:
        JsonBindingException - if a problem occurs during converters lookup/construction.
      • serialize

        public String serialize​(Object object)
        Serializes the object into a json string.
        Parameters:
        object - object to be serialized.
        Returns:
        the serialized object as a string.
        Throws:
        JsonBindingException - if there was any kind of error during serialization.
        JsonStreamException - if there was a problem during writing of the object to the output.
      • serialize

        public String serialize​(Object object,
                                GenericType<?> type)
        Serializes the object using the type of GenericType instead of using its runtime type.
        Parameters:
        object - object to be serialized.
        type - the type of the object to be serialized.
        Returns:
        json string representation.
        Throws:
        JsonBindingException
        JsonStreamException
      • serialize

        public void serialize​(Object object,
                              GenericType<?> type,
                              Writer writer)
        Serializes this object to the passed Writer, as Genson did not instantiate it, you are responsible of calling close on it.
      • serialize

        public void serialize​(Object object,
                              Writer writer)
        Serializes this object to the passed Writer, as Genson did not instantiate it, you are responsible of calling close on it.
      • serialize

        public void serialize​(Object object,
                              GenericType<?> type,
                              OutputStream output)
        Serializes this object to the passed OutputStream, as Genson did not instantiate it, you are responsible of calling close on it.
      • serialize

        public void serialize​(Object object,
                              OutputStream output)
        Serializes this object to the passed OutputStream, as Genson did not instantiate it, you are responsible of calling close on it.
      • serializeBytes

        public byte[] serializeBytes​(Object object)
        Serializes this object to its json form in a byte array.
      • serialize

        public void serialize​(Object object,
                              ObjectWriter writer,
                              Context ctx)
        Serializes this object and writes its representation to writer. As you are providing the writer instance you also must ensure to call flush and close on it when you are done.
        Parameters:
        object -
        writer - into which to write the serialized object.
        Throws:
        JsonBindingException
        JsonStreamException
      • serialize

        public void serialize​(Object object,
                              Type type,
                              ObjectWriter writer,
                              Context ctx)
        Serializes this object and writes its representation to writer. As you are providing the writer instance you also must ensure to call close on it when you are done.
      • deserialize

        public <T> T deserialize​(String fromSource,
                                 Class<T> toClass)
        Deserializes fromSource String into an instance of toClass.
        Parameters:
        fromSource - source from which to deserialize.
        toClass - type into which to deserialize.
        Throws:
        JsonBindingException
        JsonStreamException
      • deserialize

        public <T> T deserialize​(Reader reader,
                                 GenericType<T> toType)
        Deserializes the incoming json stream into an instance of T. Genson did not create the instance of Reader so it will not be closed
      • deserialize

        public <T> T deserialize​(Reader reader,
                                 Class<T> toType)
        Deserializes the incoming json stream into an instance of T. Genson did not create the instance of Reader so it will not be closed
      • deserialize

        public <T> T deserialize​(InputStream input,
                                 Class<T> toType)
        Deserializes the incoming json stream into an instance of T. Genson did not create the instance of InputStream so it will not be closed
      • deserialize

        public <T> T deserialize​(InputStream input,
                                 GenericType<T> toType)
        Deserializes the incoming json stream into an instance of T. Genson did not create the instance of InputStream so it will not be closed.
      • deserialize

        public <T> T deserialize​(byte[] input,
                                 Class<T> toType)
        Deserializes the incoming json byte array into an instance of T.
      • deserialize

        public <T> T deserialize​(byte[] input,
                                 GenericType<T> toType)
        Deserializes the incoming json byte array into an instance of T.
      • deserialize

        public <T> T deserialize​(String fromSource,
                                 Class<T> toType,
                                 Class<? extends BeanView<?>>... withViews)
      • deserializeInto

        public <T> T deserializeInto​(ObjectReader reader,
                                     T object,
                                     Context ctx)
        Deserializes the stream in the existing object. Note however that this works only for Pojos and doesn't handle nested objects (will be overridden by the values from the stream).
        Returns:
        the object enriched with the properties from the stream.
      • deserializeValues

        public <T> Iterator<T> deserializeValues​(ObjectReader reader,
                                                 GenericType<T> type)
        This can be used to deserialize in an efficient streaming fashion a sequence of objects. Note that you can use this method when your values are wrapped in an array (valid json) but also when they all are root values (not enclosed in an array). For example:
           Genson genson = new Genson();
           ObjectReader reader = genson.createReader(json);
        
           for (Iterator<LogEntry> it = genson.deserializeValues(reader, GenericType.of(LogEntry.class));
            it.hasNext(); ) {
              // do something
              LogEntry p = it.next();
           }
         
        Type Parameters:
        T -
        Parameters:
        reader - an instance of the ObjectReader to use (obtained with genson.createReader(...) for ex.), note that you are responsible of closing it.
        type - to deserialize to
        Returns:
        an iterator of T
      • aliasFor

        public <T> String aliasFor​(Class<T> clazz)
        Searches if an alias has been registered for clazz or package. If not, it will take the class full name and use it as alias. This method never returns null.
      • classFor

        public Class<?> classFor​(String alias)
                          throws ClassNotFoundException
        Searches for the class matching this alias, if none will try to use the alias as the class name.
        Parameters:
        alias -
        Returns:
        The class matching this alias.
        Throws:
        ClassNotFoundException - thrown if no class has been registered for this alias and the alias it self does not correspond to the full name of a class.
      • createWriter

        public ObjectWriter createWriter​(OutputStream os)
        Creates a new ObjectWriter with this Genson instance configuration and default encoding to UTF8.
      • createWriter

        public ObjectWriter createWriter​(OutputStream os,
                                         Charset charset)
        Creates a new ObjectWriter with this Genson instance configuration.
      • createWriter

        public ObjectWriter createWriter​(Writer writer)
        Creates a new ObjectWriter with this Genson instance configuration.
      • createReader

        public ObjectReader createReader​(InputStream is)
        Creates a new ObjectReader with this Genson instance configuration and tries to detect the encoding from the stream content.
      • createReader

        public ObjectReader createReader​(InputStream is,
                                         Charset charset)
        Creates a new ObjectReader with this Genson instance configuration.
      • createReader

        public ObjectReader createReader​(Reader reader)
        Creates a new ObjectReader with this Genson instance configuration.
      • isSkipNull

        public boolean isSkipNull()
      • isHtmlSafe

        public boolean isHtmlSafe()
      • isWithClassMetadata

        public boolean isWithClassMetadata()
      • failOnMissingProperty

        public boolean failOnMissingProperty()
      • defaultValue

        public <T> T defaultValue​(Class<T> clazz)
        Returns:
        the defined default value for type clazz or null if none is defined. Intended for internal use.
      • defaultClass

        public Class<?> defaultClass​(ValueType type)
        Get the default class to use for deserialization of the specified ValueType.
        Parameters:
        type - the ValueType to get the default class for
        Returns:
        the default class for the specified ValueType
      • setLoader

        public void setLoader​(ClassLoader loader)