Skip to content

1.x Serializing java objects

Guillaume R edited this page Apr 11, 2017 · 1 revision

Object to config

Basic use

Converting a Java object into a Config is possible with the ObjectToConfigMapper class.

If all the fields of your object are supported by the configuration, it's very simple:

ObjectToConfigMapper mapper = new ObjectToConfigMapper();
mapper.map(myObject, myConfig);

That's it! The fields' values are copied to the config, which you can for example save to a file.

Advanced use

By default, the transient fields are ignored by the mapper. If you want to include the transient fields (which can be useful when mapping objects that you don't control) you need to use the "advanced" constructor:

ObjectToConfigMapper(Map<Class<?>, ValueConverter<?, ?>> conversionMap, boolean respectTransientModifier)

Notice that it takes a "conversionMap". It is used to convert the values that aren't supported by the config into values that are.

Examples

Fields with custom types

Suppose you have an object like this:

class Object1 {
    int id;
    Infos infos;
}

class Infos {
    String name;
    String ip;

    Infos(String name, String ip) {
        this.name = name;
        this.ip = ip;
    }
}

Then you can convert it to a config like this:

Object1 myObject = // ...
Config myConfig = // ...
ObjectToConfigMapper mapper = new ObjectToConfigMapper();
mapper.map(myObject, myConfig);
   

Conversions

ObjectToConfigMapper mapper = new ObjectToConfigMapper();
mapper.addConversion(Infos.class, infos -> true, infos -> infos.name + " at " + infos.ip);// Converts every Infos to a String containing its name and ip
mapper.map(myObject, myConfig);

Include transient fields (without conversions)

ObjectToConfigMapper mapper = new ObjectToConfigMapper(new HashMap<>(), false);// empty HashMap means no conversion
mapper.map(myObject, myConfig);

Config to object

Basic use

The counterpart of the ObjectToConfigMapper is the ConfigToObjectMapper.

ConfigToObjectMapper mapper = new ConfigToObjectMapper();
mapper.map(myConfig, myObject);// Puts the config values to the corresponding fields of myObject

If you don't have an object yet and you know its class has a constructor without arguments, you can let the mapper create it:

mapper.map(myConfig, MyObject.class);// Creates a new instance of MyObject and puts the config values into it

Advanced use

You can define value conversions with the addConversion(Class, ConversionChecked, ConversionApplier) method, or by specifying a conversion map in the constructor.

Example (with the Object1 class defined above):

ConfigToObjectMapper mapper = new ConfigToObjectMapper();
mapper.addConversion(String.class, string -> string.contains(" at "), string -> {
    String[] parts = string.split(" at ");
    return new Infos(parts[0], parts[1]);
});
mapper.map(myConfig, Object1.class);