NodeJ 的方式
您可以通过节点包来实现这一点 - node-comment-json
基本上,这个库是专门设计来维护评论的,并且还允许美化 JSON 的输出。
这是我在安装软件包后可以做的npm i -g comment-json:
$ node
> const { parse, stringify } = require('comment-json')
> const parsed = parse(`{"a":"b"/*------------*/,"c":"d"}`)
> prased
{ a: 'b', c: 'd' }
> parsed['a'] = 'df'
> parsed
{ a: 'df', c: 'd' }
> stringify(parsed, null, 2)
'{\n "a": "df" /*------------*/,\n "c": "d"\n}'
现在,我知道这可以作为节点包使用。我们可以通过 node 使用它,或者如果确实需要通过 Java 使用它。
Java 解决方法
安装 NPM 和包:
使用frontend-maven-plugin,您可以安装 node/npm 以及包。所以你的 pom.xml 可能看起来像:
<plugin>
...
<executions>
<execution>
<!-- optional: you dont really need execution ids -->
<id>install node and npm</id>
<goals>
<goal>install-node-and-npm</goal>
</goals>
<!-- optional: default phase is "generate-resources" -->
<phase>generate-resources</phase>
<configuration>
<nodeVersion>v6.9.1</nodeVersion>
</configuration>
</execution>
<execution>
<id>npm install</id>
<goals>
<goal>npm</goal>
</goals>
<!-- optional: default phase is "generate-resources" -->
<phase>generate-resources</phase>
<configuration>
<!-- Install the comment-json-->
<arguments>install -g comment-json</arguments>
</configuration>
</execution>
</executions>
</plugin>
创建一个 NodeJs 脚本,它将解析参数并解析所需的逻辑
我编写了一个示例 app.js 脚本,其中除了以下参数:
- JSON:
"{\"a\":\"b\"/*------------*/,\"c\":\"d\"}"
- 改变的关键:
"a"
- 要更改的新值:
"df"
应用程序.js:
const {
parse,
stringify
} = require('comment-json');
const parsed = parse(process.argv[2]);
parsed[process.argv[3]] = process.argv[4];
console.log(stringify(parsed, null, 2))
因此,如果我将其执行为: node app.js "{\"a\":\"b\"/*------------*/,\"c\":\"d\"}" "a" "df",它将在控制台上打印:
{
"a": "df" /*------------*/,
"c": "d"
}
使用ProcessBuilder、执行脚本并从 console.log 捕获输出
也使用IOUtils
List<String> commands = new LinkedList<String>();
commands.add("node");
commands.add("app.js"); // You need the actual /path/to/app.js
commands.add("{\"a\":\"b\"/*------------*/,\"c\":\"d\"}");
commands.add("a");
commands.add("df");
ProcessBuilder processBuilder = new ProcessBuilder(commands);
String output = IOUtils.toString(processBuilder.start().getInputStream(), StandardCharsets.UTF_8);