点分隔字符串中的JSONObject

时间:2019-04-15 13:40:17

标签: java json

我正在为一个特定的问题而奋斗,我无法正确地思考。以下是问题

我有一个 map ,其键值如下所示,我只是在这里使用了字符串

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映射。到目前为止,我只是使用separtor拆分了字符串,并将其存储在如下所示的另一张地图中

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

1 个答案:

答案 0 :(得分:2)

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

    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

创建的
相关问题