1

我想从 JSON 对象中删除 blob 列。我需要检查是否有任何对象具有“@type”:“blob”,应该删除整个列。前任。以下是来自数据库的记录。'experience'、'hitpoints'、'name'、'uuid'、'image'(可选)是列。因为记录有一个blob列,即图像。它应该被丢弃。

样品输入/输出:

  {
      "experience": 14248,
      "hitpoints": 9223372036854775807,
      "name": "Aaron1",
      "uuid": "78edf902-7dd2-49a4-99b4-1c94ee286a33",
      "image": {
        "@type": "blob",
        "content_type": "image/jpeg",
        "digest": "sha1–4xlj1AKFgLdzcD7a1pVChrVTJIc=",
        "length": 3888349
      }
    },
    {
     "experience": 14252,
     "hitpoints": 92233720368512345,
     "name": "Aaron2",
     "uuid": "78edf902-7dd2-49a4-99b4-1a94ff286a45",
    }

样品 O/P:

{
  "experience": 14248,
  "hitpoints": 9223372036854775807,
  "name": "Aaron1",
  "uuid": "78edf902-7dd2-49a4-99b4-1c94ee286a33",
},
{
  "experience": 14252,
  "hitpoints": 92233720368512345,
  "name": "Aaron2",
  "uuid": "78edf902-7dd2-49a4-99b4-1a94ff286a45",
 }

有没有办法通过使用优化的 JSON 解析来实现这一点。目前,我的逻辑遵循以下步骤:

  1. 我正在使用一个函数解析整个对象,在该函数中我循环通过节点来读取对象。
  2. 在每个对象上调用“blobChecker”函数。
  3. 如果它包含 blob,则将 null 分配给节点。
  4. 跳过调用“blobChecker”的原始函数中的空节点

解析JSON的原始函数:

parseJsonNode(JsonNode node){
blobNodeChecker(node);
if(node!=null)
//The funtionality
}

blobNodeChecker 函数:

blobNodeChecker(JsonNode node) {
Boolean isBlob = false;
String blobNode = null;
Iterator<Map.Entry<String, JsonNode>> fields = node.fields();
while (fields.hasNext()) {
    Map.Entry<String, JsonNode> next = fields.next();
    String key = next.getKey();
    String val = next.getValue().toString().toLowerCase();
    if (key.equals("@type")) {
        if (val.contains("blob")) {
            isBlob = true;
            break;
    }
    }
}
if (isBlob) {
    node = null;
}
return node;
}
4

1 回答 1

0

像下面这样的东西怎么样。您可以直接读取路径并根据该路径删除节点。无需循环所有键。

String tt = " {" + 
            "      \"experience\": 14248," + 
            "      \"hitpoints\": 9223372036854775807," + 
            "      \"name\": \"Aaron1\"," + 
            "      \"uuid\": \"78edf902-7dd2-49a4-99b4-1c94ee286a33\"," + 
            "      \"image\": {" + 
            "        \"@type\": \"blob\"," + 
            "        \"content_type\": \"image/jpeg\"," + 
            "        \"digest\": \"sha1–4xlj1AKFgLdzcD7a1pVChrVTJIc=\"," + 
            "        \"length\": 3888349" + 
            "      }" + 
            "    }";
    ObjectMapper mapper = new ObjectMapper();
         mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
         JsonFactory factory = mapper.getFactory();
         JsonParser createParser = factory.createParser(tt);
         JsonNode actualObj1 = mapper.readTree(createParser);
         JsonNode path = actualObj1.path("image").path("@type");
         if( path != null && "blob".equalsIgnoreCase(path.asText())) {
             ((ObjectNode)actualObj1).remove("image");
         }
         System.out.println(actualObj1.toString());
于 2021-01-18T08:30:27.010 回答