dooo

得意分野よりも、勉強中の内容を書きたい

コロン区切りの文字列をツリー構造にする

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

public class Main {

    static ObjectMapper mapper = new ObjectMapper();

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws Exception {

        List<String> properties = Arrays.asList(
                "hoge:fuga:piyo",
                "hoge:fuga:moge",
                "hoge:ho:ge",
                "foo:bar"
        );

        JsonNode tree = parsePropertiesAsTree(properties);

        String json = mapper.writeValueAsString(tree);
        System.out.println(json); // {"hoge":{"ho":"ge","fuga":"moge"},"foo":"bar"}
    }

    private static JsonNode parsePropertiesAsTree(List<String> properties) {

        List<String[]> elementsList = properties.stream().map((property -> property.split(":"))).collect(Collectors.toList());

        ObjectNode root = mapper.createObjectNode();
        ObjectNode currentNode = null;

        for (String[] elements : elementsList) {
            currentNode = root;
            for (int i = 0; i < elements.length - 1; i++) {
                String key = elements[i];

                if (i == elements.length - 2) {
                    currentNode.put(key, elements[i + 1]);
                    break;
                }

                ObjectNode childNode = null;
                if (currentNode.has(key)) {
                    childNode = (ObjectNode) currentNode.get(key);

                } else {
                    childNode = mapper.createObjectNode();
                    currentNode.set(key, childNode);
                }

                currentNode = childNode;
            }
        }
        return root;
    }
}