簡體   English   中英

使用 Java 從 YAML 文件中刪除 Key:Value 屬性

[英]Remove Key:Value property from YAML File using Java

目標:我有一個 YAML 文件,需要從中刪除一些 key: value 屬性。 然后我想創建一個新的 YAML 文件,其中不存在已刪除的鍵:值屬性。 應從整個 YAML 文件中刪除所需的密鑰。

預期結果:應該遍歷 YAML 文件並確定要刪除的所需鍵:值,然后刪除並繼續搜索此類鍵:值屬性。

實際結果:即使遍歷 YAML 文件所需的 key: value 屬性也不會從 YAML 文件中刪除。

錯誤:沒有編譯或運行時錯誤,似乎存在邏輯錯誤。

我嘗試過的

  • 使用 Jackson ObjectMapper 讀取 YAML 文件。
  • 將所有屬性放入 LinkedHashMap 以便我可以保留訂單並刪除項目

我的邏輯:實現兩種方法

  • 一種是迭代LinkedHashMap和ArrayList對象
  • 另一個檢查特定密鑰是否可移動
  • 如果找到可移動鍵並從 LinkedHashMap 中刪除並繼續在 YAML 文件中的其他項目中搜索相同的鍵。

例如我想從 YAML 文件中刪除"originalRef": "Conditions" (鍵是字符串數據類型)。 該鍵可以包含在 LinkedHashMap 中。 此外,可能有包含多個 LinkedHashMap 的 ArrayLists。

代碼:以下是我用於這些目的的 YAML 文件。 api-test.yml這僅包含我的大 YAML 文件的一小部分。

---
swagger: '2.0'
info:
  description: |-
    Planner application is a proposal system enables user to create, manage plan .  
    It also enables network user to publish plan 
  version: '1.0'
  title: Planner API
  contact:
    name: API team
    email: apiteam@test.com
  license:
    name: Copyright © 2020 test
host: aos-dev.test.com
basePath: /unifiedplanner
tags:
  - name: Additional Fee APIs
    description: Additional Fee Controller
  - name: Condition APIs
    description: Condition Controller
  - name: Conditions Status APIs
paths:
  '/v1/{apiKey}/entity/{entityId}':
    post:
      tags:
        - Condition APIs
      summary: Save New Conditions Entity
      operationId: saveNewConditions
      consumes:
        - application/json
      produces:
        - application/json
      parameters:
        - name: Authorization
          in: header
          description: Authorization
          required: true
          type: string
        - name: apiKey
          in: path
          description: API Key
          required: true
          type: string
        - in: body
          name: conditions
          description: Conditions Entity that needs to be saved
          required: true
          schema:
            $ref: '#/definitions/Conditions'
            originalRef: Conditions
        - name: entityId
          in: path
          description: Entity ID
          required: true
          type: string
      responses:
        '200':
          description: OK
          schema:
            $ref: '#/definitions/Conditions'
            originalRef: Conditions
      deprecated: false
    put:
      tags:
        - Condition APIs
      summary: Modify / Overwrite existing Conditions Entity
      operationId: modifyConditions
      consumes:
        - application/json
      produces:
        - application/json
      parameters:
        - name: Authorization
          in: header
          description: Authorization
          required: true
          type: string
        - name: apiKey
          in: path
          description: API Key
          required: true
          type: string
        - in: body
          name: conditions
          description: Conditions Entity that needs to be updated
          required: true
          schema:
            $ref: '#/definitions/Conditions'
            originalRef: Conditions
        - name: entityId
          in: path
          description: Entity ID
          required: true
          type: string
      responses:
        '200':
          description: OK
          schema:
            $ref: '#/definitions/Conditions'
            originalRef: Conditions
      deprecated: false


下面是用於解析 YAML 文件並執行所需操作的 Java 類。

package com.aos.tools.aostool.yaml;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.*;

@Service
public class YamlProcessorGeneric {

    Logger logger = LoggerFactory.getLogger(YamlProcessorGeneric.class);

    public YamlProcessorGeneric() throws IOException {
        process();
    }

    public void process() throws IOException {
        final ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());

        final Map<String, Object> api = objectMapper.readValue(new File("api-test.yaml"),
                new TypeReference<Map<String, Object>>() {
                });

        final Map<String, Object> path = (Map<String, Object>) api.get("paths");
        extractLinkedHashMap(path);

        // write YAML file
        final Date date = Calendar.getInstance().getTime();
        objectMapper.writeValue(new File(date.toString() + "api-updated.yaml"), api);
    }

    private void extractLinkedHashMap(final Map<String,Object> itemMap) {
        itemMap.entrySet().forEach(k -> {

            // if k is a linkedhashmap and again iterate through
            if(k.getValue() instanceof LinkedHashMap) {
                extractLinkedHashMap((Map<String, Object>) k.getValue());
            }

            // if k is an arraylist then iterate through to till I find a linkedhashmap
            // so that I can remove an item.
            if(k.getValue() instanceof ArrayList) {
                ((ArrayList<?>) k.getValue()).forEach(singleItem -> {
                   if(!(singleItem instanceof String)) {
                       extractLinkedHashMap((Map<String, Object>) singleItem);
                   }
                });
            }

            // check for a specific key , if found remove from the linkedhashmap
            // but this doesn't work
            if(isRemovable(k.getKey())) {
                itemMap.remove(k);
            }

        });
    }

    private boolean isRemovable(final String key) {
        // eg:- I want to remove key with originalRef
        String removableString = "originalRef";
        return key.equals(removableString);
    }
}

對於演示過程,我將在調試應用程序時附上屏幕截圖。 itemMap所有值。

在此處輸入圖片說明

我目前沒有選擇嘗試。 請任何人都可以給我指示我在這里做錯的地方。 任何幫助將不勝感激。 再會!

如果仍然相關或有人想知道,該怎么辦。

首先,假設我們有 Yaml 對象:

public class Project  {

    private String name;
    private String description;
    private long lastUpdate;

    public Project() {
    }

    // getter, setter
}

現在我們要從數據中刪除lastUpdate字段。

  1. Project刪除 getter(更新 UI 以不使用屬性的 getter)
  2. 啟動項目
  3. 再次保存 Yaml 對象 -> 文件中的lastUpdate屬性消失了
  4. 現在您可以從Project刪除lastUpdate和 setter

如果該項目已經被很多人使用:

  1. Project刪除 getter 並清理 UI
  2. 使用一段時間后可以從文件中刪除該屬性(如果所有用戶都保存了新的 Yaml 對象)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM