133 words
1 minutes
How to convert java object to properties format

Introduction#

How to convert java object to properties format?

This article will show you how to convert java object to properties format.

Add Dependencies#

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-properties</artifactId>
    <version>2.12.5</version>
</dependency>

Java Object To Properties Map#

public class PropsUtils {
    
    /**
     *
     * Convert java object to properties: all fields, getter methods and is methods into properties map.
     *
     * @param object
     * @param <T>
     * @return
     */
    public <T> Map<String, String> toProperties(T object) throws IOException {
        JavaPropsMapper mapper = JavaPropsMapper.builder().build();
        JavaPropsSchema javaPropsSchema = JavaPropsSchema.emptySchema().withWriteIndexUsingMarkers(true);
        return mapper.writeValueAsMap(entity, javaPropsSchema);
    }

    /**
     *
     * Convert java object to properties: all fields only into properties map.
     *
     * @param object
     * @param <T>
     * @return
     */
    public <T> Map<String, String> toPropertiesOnlyFields(T object) throws IOException {
        JavaPropsMapper mapper = JavaPropsMapper.builder()
                .visibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY)
                .visibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE)
                .visibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.NONE).build();
        JavaPropsSchema javaPropsSchema = JavaPropsSchema.emptySchema().withWriteIndexUsingMarkers(true);
        return mapper.writeValueAsMap(entity, javaPropsSchema);
    }
}
How to convert java object to properties format
https://semusings.dev/posts/2021/2021-09-14-how-to-convert-java-object-to-properities-format/
Author
Bhuwan Prasad Upadhyay
Published at
2021-09-14