有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java无法从YAML文件中删除特定的key:value

目标:我想从YAML文件中删除特定键及其关联值

预期结果orginalRef键及其值应从YAML文件中删除,并应生成新的YAML文件

实际结果responses属性下的orginalRef值不会删除

错误消息:没有错误消息

我尝试的内容:我有一个招摇过市的YAML文件,我只是将其加载到Jackson ObjectMapper中,并尝试从该YAML文件中删除一些键。然后用我所做的更改生成一个新的YAML文件

代码: 下面是我巨大的YAML文件的一部分。它的名字是api.yaml

---
swagger: "2.0"
info:
  description: "Planner application is a proposal system enables user to create, manage\
    \ plan .  \nIt 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"
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"
      - 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"
      - name: "entityId"
        in: "path"
        description: "Entity ID"
        required: true
        type: "string"
      responses:
        "200":
          description: "OK"
          schema:
            $ref: "#/definitions/Conditions"
            originalRef: "Conditions"
      deprecated: false
definitions:
  AbstractCondition:
    type: "object"
    properties:
      externalTrafficSystem:
        $ref: "#/definitions/ExternalTrafficSystem"
        originalRef: "ExternalTrafficSystem"
      id:
        type: "string"
      version:
        type: "integer"
        format: "int64"
    title: "AbstractCondition"

如您所见,我只想从上述YAML文件中的originalRef属性中删除responses键及其值

下面是我的YamlProcessor。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.springframework.stereotype.Service;

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

@Service
public class YamlProcessor {

    public YamlProcessor() 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.yaml"),
                new TypeReference<Map<String, Object>>() {
                });

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

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

    private void processPath(final Map<String, Object> paths) {
        paths.entrySet().forEach(path -> {
            if (null != path) {
                final Map<String, Object> level1Child = (Map<String, Object>) path.getValue();
                if (null != level1Child) {
                    level1Child.entrySet().forEach(method -> {
                        final Map<String, Object> methodValues = (Map<String, Object>) method.getValue();
                        methodValues.entrySet().forEach(methodValue -> {
                            if (null != methodValue && methodValue.getKey().equals("parameters")) {
                                final List<Object> paramValue = (List<Object>) methodValue.getValue();
                                paramValue.forEach(paramValueChild -> {
                                    if (null != paramValueChild) {
                                        final Map<String, Object> paramMap = (HashMap<String, Object>) paramValueChild;
                                        paramMap.entrySet().forEach(k -> {
                                            if (k.getKey().contains("schema")) {
                                                final Map<String, Object> schema = (HashMap<String, Object>) k.getValue();
                                                // this line works fine , this will remove all the originalRef keys under parameters property
                                                schema.remove("originalRef"); 
                                            }
                                        });
                                    }
                                });
                            }

                            // this is where I'm currently getting stucked.
                            if (null != methodValue && methodValue.getKey().equals("responses")) {
                                Map<String,Object> value = (HashMap<String,Object>) methodValue.getValue();
                                if(value.containsKey("200")) {
                                    value.entrySet().forEach(k -> {
                                        if(k.getKey().contains("schema")) {
                                            Map<String,Object> responseSchema = (HashMap<String,Object>)k.getValue();
                                            responseSchema.remove("originalRef");
                                        }
                                    });
                                }
                            }
                        });
                    });
                }
            }
        });
    }
}

当我运行应用程序时,它运行良好,没有任何错误。还将生成新的YAML文件。 但是在新的YAML文件中,responses属性下仍然有originlaRef key contains。 谁来告诉我我做错了什么。 任何帮助都将不胜感激。 干杯你好


共 (1) 个答案

  1. # 1 楼答案

    最后,通过对代码进行实验,我终于能够获得所需的输出

    以下是我的有效解决方案

    if(value.containsKey("200")) {
        value.entrySet().forEach(k -> {
            Map<String,Object> responseSchema = (HashMap<String,Object>) k.getValue();
            responseSchema.entrySet().forEach(a -> {
                if(a.getKey().contains("schema")) {
                    Map<String,Object> reSchema = (HashMap<String,Object>)a.getValue();
                    reSchema.entrySet().forEach(c -> {
                        if(c.getKey().contains("items")) {
                            Map<String,Object> innerSchema = (HashMap<String,Object>) c.getValue();
                            innerSchema.remove("originalRef");
                        }
                    });
                }
            });
        });
    }