我在字符串中有一个 JSON 内容,有时它有必须删除的数字标签。
下面是示例 JSON 内容
{
"Test": {
"P1": false,
P2": {
"2000": [
{
"DP": "DP TEST",
"id": "ID TEST"
}
],
"4000": [
{
"DP": "DP TEST",
"id": "ID TEST"
}
],
"5000": [
{
"DP": "DP TEST",
"id": "ID TEST"
}
],
"8000": [
{
"DP": "DP TEST",
"id": "ID TEST"
}
],
"6000": [
{
"DP": "DP TEST",
"id": "ID TEST"
}
]
},
"P3": "XYZ",
"P4": ABC,
"VL": "",
"PL": [{
"start_date": 1496480880.0,
"id": "TEST1"
}
],
},
"PS": "AMD",
"links": [{
"LOC": "en-US",
"PS": "AMD"
}, {
"LOC": "fr-CA",
"PS": "AMD"
}
]
}
在上述情况下,“P2”标签具有数字键,在这种情况下,我们需要将其显示为将字符串转换为 JSON 后的样子。这意味着,我们需要删除带有数字键的标签。
我也尝试过 org.json、org.json.simple 和 com.gson,但似乎没有任何效果。
我可以使用下面的代码片段读取每一行
public static void printJson(JsonElement jsonElement) {
// Check whether jsonElement is JsonObject or not
if (jsonElement.isJsonObject()) {
Set<Entry<String, JsonElement>> ens = ((JsonObject) jsonElement).entrySet();
if (ens != null) {
// Iterate JSON Elements with Key values
for (Entry<String, JsonElement> en : ens) {
try{
Integer.parseInt(en.getKey());
break;
}catch(NumberFormatException ex){
if("".equals(str)){
str = "\"" + en.getKey() + "\": {";
}else{
str = str + "\"" + en.getKey() + "\": {";
}
System.out.println(en.getKey() + "-----" + en.getValue());
}
printJson(en.getValue());
}
}
}
// Check whether jsonElement is Arrary or not
else if (jsonElement.isJsonArray()) {
JsonArray jarr = jsonElement.getAsJsonArray();
// Iterate JSON Array to JSON Elements
for (JsonElement je : jarr) {
printJson(je);
}
}
// Check whether jsonElement is NULL or not
else if (jsonElement.isJsonNull()) {
// print null
System.out.println("null");
}
// Check whether jsonElement is Primitive or not
else if (jsonElement.isJsonPrimitive()) {
// print value as String
if("".equals(str)){
str = "\"" + jsonElement.getAsString() + "\"";
}else{
str = str + "\"" + jsonElement.getAsString() + "\"";
}
System.out.println(jsonElement.getAsString());
}
}
但我无法删除数字键控标签。有人可以帮我解决这个问题吗?
最佳答案
如果你想删除数字的 JSONObject
键,你可以这样做:
private static void strip(JSONObject obj) {
for (Iterator<String> keyIter = obj.keys(); keyIter.hasNext(); ) {
String key = keyIter.next();
if (key.matches("\\d+"))
keyIter.remove();
else
strip(obj.get(key));
}
}
private static void strip(Object value) {
if (value instanceof JSONObject) {
strip((JSONObject) value);
} else if (value instanceof JSONArray) {
for (Object elem : (JSONArray) value)
strip(elem);
}
}
测试
String input = new String(Files.readAllBytes(Paths.get("path/to/file.json")), StandardCharsets.US_ASCII);
JSONObject obj = new JSONObject(input);
strip(obj);
System.out.println(obj.toString(2));
输出
{
"PS": "AMD",
"Test": {
"P1": false,
"P2": {},
"P3": "XYZ",
"P4": "ABC",
"VL": "",
"PL": [{
"id": "TEST1",
"start_date": 1.49648088E9
}]
},
"links": [
{
"LOC": "en-US",
"PS": "AMD"
},
{
"LOC": "fr-CA",
"PS": "AMD"
}
]
}
关于java - 使用java删除动态json中的数字标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44810651/