java属性为json [英] java properties to json

查看:184
本文介绍了java属性为json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的方法可以将带点符号的属性转换为json

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

IE

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

TO

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


推荐答案

不是简单的方法,但我设法使用 Gson 库来做到这一点。结果将在
jsonBundle 字符串中。在这种情况下,我们得到属性或包:

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

对于此实现,必须转换 ResourceBundle Map 包含 String 作为键, String 作为值。

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

我必须创建自定义 JSONSerializer 使用 Gson 获取 Map< String,String>

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

这是创建JSON的主要逻辑:

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

最后,如果有一个键 person.name.firstname ,其值 John ,它将转换为此类 JSON

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

这篇关于java属性为json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆