如何使用Java查找和替换json值?

时间:2018-07-07 09:08:49

标签: java json

场景:

我的情况是,从文件中查找并替换给定的JSONArray,JSON对象。
例如,我想用我的新值和其他几个字段替换名为 host 的JSONArray字段之一。

Search String: "host"
Replace String: ["environment"]

尝试过的解决方案:

我写了一个程序来达到同样的目的。它正在替换单个请求项。

问题:

它不适用于所有其他请求。如何用新值替换所有请求的“主机”键?

JSON

{
    "item": [{
        "request": {
            "method": "get",
            "header": [{
                "value": "Bearer ",
                "key": "Authorization"
            }, {
                "value": "application/com.platform.type.v1+json",
                "key": "Accept"
            }],
            "description": "Search Types",
            "body": {},
            "url": {
                "path": ["type", "v2", "Types"],
                "protocol": "https",
                "query": [{
                    "value": "",
                    "key": "sortBy"
                }, {
                    "value": "",
                    "key": "pageSize"
                }],
                "host": ["api", "theory", "com"],
                "raw": "https://api.theory.com/type/v2/Types?sortBy=pageSize"
            }
        },
        "response": [],
        "name": "/Types"
    }, {
        "request": {
            "method": "post",
            "header": [{
                "value": "Bearer ",
                "key": "Authorization"
            }, {
                "value": "application/com.platform.type.v1+json",
                "key": "Accept"
            }, {
                "value": "application/com.platform.type.v1+json",
                "key": "Content-Type"
            }, {
                "value": "application/com.platform.type.v1+json",
                "key": "Content-Type"
            }],
            "description": "Create a new type",
            "body": {
                "mode": "raw",
                "raw": ""
            },
            "url": {
                "path": ["type", "v2", "Types"],
                "protocol": "https",
                "host": ["api", "theory", "com"],
                "raw": "https://api.theory.com/type/v2/attributeTypes"
            }
        },
        "response": [],
        "name": "/Types"
    }]
}

Java代码

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

import org.apache.commons.io.FileUtils;
import org.json.JSONArray;
import org.json.JSONObject;

public class ServiceCollection {

    private final String filePath;
    private boolean isArray;
    private JSONObject collections;

    private ServiceCollection(final Builder builder) {
        this.filePath = builder.filePath;
        this.collections = builder.collections;
    }

    public JSONObject asObject() {
        return this.collections;
    }

    public JSONArray asArray() {
        JSONArray arrayCollections = new JSONArray();
        Iterator<?> keysIterator = this.collections.keys();
        while (keysIterator.hasNext()) {
            String key = (String) keysIterator.next();
            arrayCollections.put(this.collections.get(key));
        }
        return arrayCollections;
    }

    public static class Builder {

        private String filePath;
        private JSONObject collections = null;
        private JSONArray persistedArray;
        private JSONObject persistedObject;
        private boolean isArray;

        public Builder withContentParser(final String filePath) {
            this.filePath = filePath;
            this.collections = getParsedCollectionObjects();
            return this;
        }

        public Builder withNode(String nodeHierachy) {
            findAndStoreObject(nodeHierachy);
            return this;
        }

        public Builder withNodeIndex(int nodeIndex) {
            findAndStoreObject(nodeIndex);
            return this;
        }

        public Builder withReplace(final String findString, final String replaceString) {
            if (isArray) {
                int length = this.persistedArray.length();
                if (length > 0) {
                    while (length > -1) {
                        this.persistedArray.remove(length);
                        length--;
                    }
                }
                this.persistedArray.put(replaceString);
                this.collections.put(findString, this.persistedArray);

            } else {
                this.collections.put(findString, replaceString);
            }
            return this;
        }

        public ServiceCollection builder() {
            return new ServiceCollection(this);
        }

        private void findAndStoreObject(int nodeIndex) {
            JSONObject thisObject = (JSONObject) persistedArray.get(nodeIndex);
            this.persistedObject = thisObject;
        }

        private void findAndStoreObject(String nodeHierachy) {
            if (persistedObject == null) {
                this.persistedObject = collections;
            }
            try {
                JSONArray thisObject = (JSONArray) persistedObject.get(nodeHierachy);
                this.persistedArray = thisObject;
                this.isArray = true;
            } catch (Exception e) {
                JSONObject thisObject = (JSONObject) persistedObject.get(nodeHierachy);
                this.persistedObject = thisObject;
                this.isArray = false;
            }
        }

        private JSONObject getParsedCollectionObjects() {
            JSONObject collectionObjects = null;
            if (collections == null) {
                File collectionsFile = new File(filePath);
                try {
                    String collectionsContent = FileUtils.readFileToString(collectionsFile, "utf-8");
                    if (!collectionsContent.isEmpty()) {
                        collectionObjects = new JSONObject(collectionsContent);
                    }
                } catch (IOException e) {
                }
            }
            return collectionObjects;
        }
    }
}

致电构建者:

String filePath = "<JSON File>";
String replacedString = factory().withContentParser(filePath).withNode("item").withNodeIndex(0).withNode("request").withNode("url").withNode("host").withReplace("host", "{{environment}}").builder().asObject().toString();

0 个答案:

没有答案