我有这样的杰森:

{
"_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)

最佳答案

您可以遍历键,对键进行规范化,然后递归继续,只要该值是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;
}

10-08 13:32