1

我正在努力解决一个我无法正确思考的特定问题。以下是问题

我有一个键值如下的地图,我只是在这里使用了字符串

String key = "activate.message.success"
String value = "success"
String key1 = "activate.title"
String value1 = "Good Title"
String key2 = "activate.message.error"
String value2 = "error"
String key3 = "activate.message.short.poll"
String value3 = "This is short poll"

我需要建立一个像下面这样的json

{
  "activate":{
       "message":{
         "success":"success",
         "error":"error",
         "short":{
             "poll":"This is short poll"
        }
     },
       "title":"Good Title"
   }
}

我想不出这个用例的合适解决方案并挣扎了 3 个小时。我想过使用递归,但我不知道我该怎么做。请帮助解决这个问题。我为此使用 java,我应该使用通用 JSONObject 来解决,因为没有 POJO 映射。到目前为止,我刚刚使用分隔符拆分字符串并存储在另一个地图中,如下所示

public Map<String, Object> getJsonObjectFromKeyValueMap(Map<String, String> stringValueMap,
        Map<String, Object> stringObjectMap) {

    for (Entry entry : stringValueMap.entrySet()) {
        String[] keyValueArrayString = entry.getKey().toString().split("\\.");
        int sizeOfMap = keyValueArrayString.length;

        int i = 0;
        String concatString = "";
        for (String processKey : keyValueArrayString) {

            if (i < sizeOfMap - 1) {
                concatString += processKey + ".";
                stringObjectMap.put(concatString, (Object) new JSONObject());
            } else {
                concatString += processKey;
                stringObjectMap.put(concatString, entry.getValue());
                concatString = "";
            }
            i++;
        }

    }
    return stringObjectMap;
}
4

1 回答 1

3

首先,让我们将您的数据更新为适当的地图:

    Map<String, String> data = new HashMap<>();
    data.put("activate.message.success", "success");
    data.put("activate.title", "Good Title");
    data.put("activate.message.error", "error");
    data.put("activate.message.short.poll", "This is short poll");

然后,您的逻辑非常接近,对于除最后一个节点之外的每个节点,您创建一个新的 JSONObject,对于最后一个节点,您插入值。

如果您尝试构建 JSONObject 而不是直接构建地图,那么您已经获得了相当不错的结果,而且在某种程度上是一个结果。

下面将迭代一个Map<String, String>数据。对于每个条目,我们拆分获取节点的密钥。

然后,我们只需要移动到 中json,如果一个节点不存在,我们就创建它。然后,对于最后一个值,创建该值。

public static JSONObject build(Map<String, String> data) {
    JSONObject json = new JSONObject();
    //Iterate the map entries
    for (Entry<String, String> e : data.entrySet()) {
        String[] keys = e.getKey().split("\\.");

        // start from the root
        JSONObject current = json;
        for (int i = 0; i < keys.length; ++i) {
            String key = keys[i];

            //Search for the current node
            try {
                //If it exist, do nothing
                current = current.getJSONObject(key);
            } //If it does not exist
            catch (JSONException ex) {
                //Is it the last node, create the value
                if (i == keys.length - 1) { 
                    current.put(key, e.getValue());
                } //Not the last node, create a new JSONObject
                else { 
                    JSONObject tmp = new JSONObject();
                    current.put(key, tmp);
                    current = tmp; //Always replace current with the last node to go deeped each iteration
                }
            }
        }

    }

    return json;
}

和例子:

public static void main(String[] args) {
    Map<String, String> data = new HashMap<>();
    data.put("activate.message.success", "success");
    data.put("activate.title", "Good Title");
    data.put("activate.message.error", "error");
    data.put("activate.message.short.poll", "This is short poll");

    JSONObject json = build(data);
    System.out.println(json.toString(4));
}

输出:

{"activate": {
    "message": {
        "success": "success",
        "short": {"poll": "This is short poll"},
        "error": "error"
    },
    "title": "Good Title"
}}

注意:我使用异常来检查密钥是否存在,如果地图很大,这可能会产生一些影响,因此您可以简单地使用:

if(current.isNull(key)){
    if (i == keys.length - 1) {
        current.put(key, e.getValue());
    } else {
        JSONObject tmp = new JSONObject();
        current.put(key, tmp);
        current = tmp;
    }
} else {
    current = current.getJSONObject(key);
}

这是使用org.json/json创建的

于 2019-04-15T14:22:31.533 回答