java 属性到 json

2022-09-01 03:59:43

有没有一种简单的方法可以将带有点表示法的属性转换为json

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

{
 "server": {
    "host": "foo.bar",
    "port": 1234
  }
} 

答案 1

这不是简单的方法,但我设法使用库做到这一点。结果将显示在字符串中。在这里,我们获取本例中的属性或捆绑包:GsonjsonBundle

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);

为此,必须将其转换为包含作为键和值。ResourceBundleMapStringString

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;
}

我不得不使用以下内容创建自定义:JSONSerializerGsonMap<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;
    }
}

以下是创建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();
        }
   }

最后,如果有一个带值的键,它将被转换为这样的:person.name.firstnameJohnJSON

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

希望这将有助于:)


答案 2

使用 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());
}