Java creating json from translation key value pairs

Viewed 123

I have a sorted list (by key) of key value pairs like this:

administration.edit.error.type1 = val1
administration.edit.error.type2 = val2
administration.edit.success.type1 = val3
administration.label.button.close = val4
administration.label.button.edit = val5
home.label.button.open = val6

I would want to convert this list to

{
    "administration": {
        "edit": {
            "error": {
                "type1": val1,
                "type2": val2,
            },
            "success": {
                "type1": val3
            }
        },
        "label": {
            "button": {
                "close": val4,
                "edit": val5,
            }
        }
    },
    "home": {
        "label": {
            "button": {
                "open": val6
            }
        }
    }
}

The provided input list is unknown, as well as the levels connected by the dots
My approach would have been to recursively, iterate through the list and create JsonNodes with Jackson mapper. Is there a more efficient way to do this? Is there maybe a library that can already do this?

1 Answers

JavaPropsMapper, from jackson-dataformat-properties does the job

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.javaprop.JavaPropsMapper;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Properties;

public class Application {

  public static void main(String[] args) throws IOException {

    FileReader fr = new FileReader("/tmp/test.properties");
    Properties properties = new Properties();
    properties.load(fr);

    HashMap map = new JavaPropsMapper().readPropertiesAs(properties, HashMap.class);
    System.out.println(map);

    String json = new ObjectMapper().writeValueAsString(map);
    System.out.println(json);

  }
}

Output for your sample-file:

{administration={edit={error={type2=val2, type1=val1}, success={type1=val3}}, label={button={close=val4, edit=val5}}}, home={label={button={open=val6}}}}
{"administration":{"edit":{"error":{"type2":"val2","type1":"val1"},"success":{"type1":"val3"}},"label":{"button":{"close":"val4","edit":"val5"}}},"home":{"label":{"button":{"open":"val6"}}}}

The sample uses these dependencies:

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.11.1</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-properties</artifactId>
            <version>2.11.1</version>
        </dependency>

Related