Vit*_*hov 30 java json properties
有没有一种简单的方法将带点符号的属性转换为json
IE
server.host=foo.bar
server.port=1234
Run Code Online (Sandbox Code Playgroud)
至
{
"server": {
"host": "foo.bar",
"port": 1234
}
}
Run Code Online (Sandbox Code Playgroud)
不是简单的方法,但我设法使用Gson
库来做到这一点.结果将在
jsonBundle
String中.在这种情况下,我们获取属性或包:
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);
Run Code Online (Sandbox Code Playgroud)
为此,ResourceBundle
必须将实现转换为Map
包含String
键和String
值.
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;
}
Run Code Online (Sandbox Code Playgroud)
我不得不创建自定义JSONSerializer
使用Gson
为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;
}
}
Run Code Online (Sandbox Code Playgroud)
这是创建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();
}
}
Run Code Online (Sandbox Code Playgroud)
最后,如果有一个person.name.firstname
有价值的键John
,它将被转换为JSON
:
{
"person" : {
"name" : {
"firstname" : "John"
}
}
}
Run Code Online (Sandbox Code Playgroud)
希望这会有所帮助:)
使用 lightbend 配置 java 库 ( 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());
}
Run Code Online (Sandbox Code Playgroud)
小智 3
这非常简单,下载并添加到您的库中: https: //code.google.com/p/google-gson/
Gson gsonObj = new Gson();
String strJson = gsonObj.toJson(yourObject);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
33875 次 |
最近记录: |