java properties to json

后端 未结 10 1579
情书的邮戳
情书的邮戳 2020-12-13 18:06

Is there an easy way to convert properties with dot notation to json

I.E

server.host=foo.bar
server.port=1234

TO

{
         


        
相关标签:
10条回答
  • 2020-12-13 18:37

    Using lightbend config java library (https://github.com/lightbend/config)

    String toHierarchicalJsonString(Properties props) {
      com.typesafe.config.Config config = com.typesafe.config.ConfigFactory.parseProperties(props);
      return config.root().render(com.typesafe.config.ConfigRenderOptions.concise());
    }
    
    0 讨论(0)
  • 2020-12-13 18:42

    Look at this https://github.com/nzakas/props2js. You can use it manually or fork and use in your project.

    0 讨论(0)
  • 2020-12-13 18:43

    It is pretty easy, download and add to your lib: https://code.google.com/p/google-gson/

    Gson gsonObj = new Gson();
    String strJson =  gsonObj.toJson(yourObject);
    
    0 讨论(0)
  • 2020-12-13 18:49

    A little bit recursion and Gson :)

    public void run() throws IOException {
    
        Properties properties = ...;
    
        Map<String, Object> map = new TreeMap<>();
    
        for (Object key : properties.keySet()) {
            List<String> keyList = Arrays.asList(((String) key).split("\\."));
            Map<String, Object> valueMap = createTree(keyList, map);
            String value = properties.getProperty((String) key);
            value = StringEscapeUtils.unescapeHtml(value);
            valueMap.put(keyList.get(keyList.size() - 1), value);
        }
    
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String json = gson.toJson(map);
    
        System.out.println("Ready, converts " + properties.size() + " entries.");
    }
    
    @SuppressWarnings("unchecked")
    private Map<String, Object> createTree(List<String> keys, Map<String, Object> map) {
        Map<String, Object> valueMap = (Map<String, Object>) map.get(keys.get(0));
        if (valueMap == null) {
            valueMap = new HashMap<String, Object>();
        }
        map.put(keys.get(0), valueMap);
        Map<String, Object> out = valueMap;
        if (keys.size() > 2) {
            out = createTree(keys.subList(1, keys.size()), valueMap);
        }
        return out;
    }
    
    0 讨论(0)
  • 2020-12-13 18:53

    Not the easy way, but I managed to do that using Gson library. The result will be in the jsonBundle String. Here we getting the properties or bundles in this case:

    final ResourceBundle bundle = ResourceBundle.getBundle("messages");
    final Map<String, String> bundleMap = resourceBundleToMap(bundle);
    
    final Type mapType = new TypeToken<Map<String, String>>(){}.getType();
    
    final String jsonBundle = new GsonBuilder()
            .registerTypeAdapter(mapType, new BundleMapSerializer())
            .create()
            .toJson(bundleMap, mapType);
    

    For this implementation ResourceBundle have to be converted to Map containing String as a key and String as a value.

    private static Map<String, String> resourceBundleToMap(final ResourceBundle bundle) {
        final Map<String, String> bundleMap = new HashMap<>();
    
        for (String key: bundle.keySet()) {
            final String value = bundle.getString(key);
    
            bundleMap.put(key, value);
        }
    
        return bundleMap;
    }
    

    I had to create custom JSONSerializer using Gson for Map<String, String>:

    public class BundleMapSerializer implements JsonSerializer<Map<String, String>> {
    
        private static final Logger LOGGER = LoggerFactory.getLogger(BundleMapSerializer.class);
    
        @Override
        public JsonElement serialize(final Map<String, String> bundleMap, final Type typeOfSrc, final JsonSerializationContext context) {
            final JsonObject resultJson =  new JsonObject();
    
            for (final String key: bundleMap.keySet()) {
                try {
                    createFromBundleKey(resultJson, key, bundleMap.get(key));
                } catch (final IOException e) {
                    LOGGER.error("Bundle map serialization exception: ", e);
                }
            }
    
            return resultJson;
        }
    }
    

    And here is the main logic of creating JSON:

    public static JsonObject createFromBundleKey(final JsonObject resultJson, final String key, final String value) throws IOException {
        if (!key.contains(".")) {
            resultJson.addProperty(key, value);
    
            return resultJson;
        }
    
        final String currentKey = firstKey(key);
        if (currentKey != null) {
            final String subRightKey = key.substring(currentKey.length() + 1, key.length());
            final JsonObject childJson = getJsonIfExists(resultJson, currentKey);
    
            resultJson.add(currentKey, createFromBundleKey(childJson, subRightKey, value));
        }
    
        return resultJson;
    }
    
        private static String firstKey(final String fullKey) {
            final String[] splittedKey = fullKey.split("\\.");
    
            return (splittedKey.length != 0) ? splittedKey[0] : fullKey;
        }
    
        private static JsonObject getJsonIfExists(final JsonObject parent, final String key) {
            if (parent == null) {
                LOGGER.warn("Parent json parameter is null!");
                return null;
            }
    
            if (parent.get(key) != null && !(parent.get(key) instanceof JsonObject)) {
                throw new IllegalArgumentException("Invalid key \'" + key + "\' for parent: " + parent + "\nKey can not be JSON object and property or array in one time");
            }
    
            if (parent.getAsJsonObject(key) != null) {
                return parent.getAsJsonObject(key);
            } else {
                return new JsonObject();
            }
       }
    

    In the end, if there were a key person.name.firstname with value John, it will be converted to such JSON:

    {
         "person" : {
             "name" : {
                 "firstname" : "John"
             }
         }
    }
    

    Hope this will help :)

    0 讨论(0)
  • 2020-12-13 18:53

    just use org.json.JSONObject constructor that receives a Map (which Properties extends):

    JSONObject jsonProps = new JSONObject(properties);
    jsonProps.toString();
    

    If you don't already have the properties loaded you can do that from a file

    Properties properties= new Properties();
    File file = new File("/path/to/test.properties");
    FileInputStream fileInput = new FileInputStream(file);
    properties.load(fileInput);
    

    If you want to do the reverse, and read a json string into a prop file you can use com.fasterxml.jackson.databind.ObjectMapper:

    HashMap<String,String> result = new ObjectMapper().readValue(jsonPropString, HashMap.class);
    Properties props = new Properties();
    props.putAll(result);
    
    0 讨论(0)
提交回复
热议问题