首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将java属性转换为json

将java属性转换为json
EN

Stack Overflow用户
提问于 2014-05-26 21:50:02
回答 7查看 45.4K关注 0票数 38

有没有一种简单的方法可以将点符号的属性转换成json?

I.E

代码语言:javascript
复制
server.host=foo.bar
server.port=1234

代码语言:javascript
复制
{
 "server": {
    "host": "foo.bar",
    "port": 1234
  }
} 
EN

回答 7

Stack Overflow用户

发布于 2014-08-07 16:54:37

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

代码语言:javascript
复制
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转换为包含String作为键和String作为值的Map

代码语言:javascript
复制
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;
}

我必须使用GsonMap<String, String>创建自定义JSONSerializer

代码语言:javascript
复制
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的主要逻辑:

代码语言:javascript
复制
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();
        }
   }

最后,如果有一个值为John的键person.name.firstname,它会被转换成这样的JSON

代码语言:javascript
复制
{
     "person" : {
         "name" : {
             "firstname" : "John"
         }
     }
}

希望这能有所帮助:)

票数 8
EN

Stack Overflow用户

发布于 2019-03-02 01:40:00

使用lightbend配置java库(https://github.com/lightbend/config)

代码语言:javascript
复制
String toHierarchicalJsonString(Properties props) {
  com.typesafe.config.Config config = com.typesafe.config.ConfigFactory.parseProperties(props);
  return config.root().render(com.typesafe.config.ConfigRenderOptions.concise());
}
票数 5
EN

Stack Overflow用户

发布于 2014-05-26 21:58:01

下载并添加到您的库中非常简单:https://code.google.com/p/google-gson/

代码语言:javascript
复制
Gson gsonObj = new Gson();
String strJson =  gsonObj.toJson(yourObject);
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23871694

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档