Java json对象替换键名称

时间:2020-04-18 17:24:41

标签: java json loops key

我有这样的杰森:

{
"_id" : ObjectId("5e99f6d16cbddf7dad26557f"),
"channel_id" : 49066,
"timestamp" : NumberLong(1580982302003),
"values" : {
    "some id" : "81151501",
    "some title" : "Some title",
    "some address" : "https://www.some-address.com",
    "new hash" : {
        "some value" : "5",
        "other value" : " 54.10 BRL"
    },
    "wrong values" : "This text have wrong & values & and netx is wrong too & and this &"
},
"null value" : null,
"zero integer" : 0
}

我需要遍历每个键,并用snake_case替换空格,例如从other valueother_value

此外,我想通过用&替换字符_来检查循环中的每个值,例如:

This text have wrong & values & and netx is wrong too & and this &This text have wrong _ values _ and netx is wrong too _ and this _

我的json对象来自:

JSONobject jsonObject = new JSONobject(jsonString)

1 个答案:

答案 0 :(得分:1)

只要值是JSONObject,就可以遍历键,对键进行规范化并递归继续。如果不是,那么您也可以将值标准化。所以这看起来像这样:

static JSONObject normalize(JSONObject object) throws JSONException {
    JSONObject result = new JSONObject();
    Iterator iterator = object.keys();

    while (iterator.hasNext()) {
        String key = (String) iterator.next();
        String normalizedKey = key.replace(" ", "_");

        Object inner = object.get(key);

        if (inner instanceof JSONObject) {
            result.put(normalizedKey, normalize((JSONObject) inner));
        } else if (inner instanceof String) {
            result.put(normalizedKey, object.getString(key).replace("&", "_"));
        } else {
            result.put(normalizedKey, inner);
        }
    }

    return result;
}

该库的最新版本还提供了获取密钥集的功能,这将使密钥循环更为简洁:

static JSONObject normalized(JSONObject object) {
    JSONObject result = new JSONObject();

    object.keySet().forEach(key -> {
        String normalizedKey = key.replace(" ", "_");
        Object value = object.get(key);

        if (value instanceof JSONObject) {
            result.put(normalizedKey, normalized((JSONObject) value));
        } else if (value instanceof String) {
            result.put(normalizedKey, ((String) value).replace("&", "_"));
        } else {
            result.put(normalizedKey, value);   
        }
    });     
    return result;
}
相关问题