Easy way to access nested properties on a map

I use the following code to directly access any property in the structure of nested maps, as in the example.

import com.google.common.collect.ImmutableMap;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.config.YamlProcessor;
import org.springframework.core.env.MapPropertySource;

import java.util.Map;

public class MapPropertySourceLearningTest {

    @Test
    public void testFlattenedMap() {
        Map map = ImmutableMap.of(
                "meta", ImmutableMap.of(
                        "pagination", ImmutableMap.of(
                                "position", "1",
                                "itemsPerPage", "50",
                                "totalPages", "9",
                                "totalItems", "438"
                        )
                )
        );

        MapPropertySource source = new MapPropertySource("map", new YamlProcessor() {
            public Map<String, Object> flatten(Map<String, Object> source) {
                return super.getFlattenedMap(source);
            }
        }.flatten(map));

        Assert.assertEquals("1", source.getProperty("meta.pagination.position"));
        Assert.assertEquals("9", source.getProperty("meta.pagination.totalPages"));
    }


}

I do not like to extend the YamlProcessor class. ¿Is there a better way to do the same?

+4
source share
1 answer

Either PropertyUtils.getProperty (returns an object) or BeanUtils.getProperty (returns a string) in Apache Commons BeanUtils will meet your needs. However, they throw some cumbersome exceptions, so you might want to create your own wrapper method that handles exceptions as you see fit.

Assert.assertEquals("1", PropertyUtils.getProperty(map, "meta.pagination.position"));
Assert.assertEquals("9", PropertyUtils.getProperty(map, "meta.pagination.totalPages"));
Assert.assertEquals("1", BeanUtils.getProperty(map, "meta.pagination.position"));
Assert.assertEquals("9", BeanUtils.getProperty(map, "meta.pagination.totalPages"));
+1
source

All Articles