将具有重复键的 JSON 对象转换为 JSON 数组
我有一个从包含重复键的数据库中获取的 JSON 字符串.我想通过将它们的值组合到一个数组中来删除重复的键.
I have a JSON string that I get from a database which contains repeated keys. I want to remove the repeated keys by combining their values into an array.
例如
输入
{
"a":"b",
"c":"d",
"c":"e",
"f":"g"
}
输出
{
"a":"b",
"c":["d","e"],
"f":"g"
}
实际数据是一个可能嵌套的大文件.我不会提前知道有什么或多少对.
The actual data is a large file that may be nested. I will not know ahead of time what or how many pairs there are.
为此我需要使用 Java.org.json 因为key 重复而抛出异常,gson 可以解析字符串但是每个重复的key 都会覆盖最后一个.我需要保留所有数据.
I need to use Java for this. org.json throws an exception because of the repeated keys, gson can parse the string but each repeated key overwrites the last one. I need to keep all the data.
如果可能,我想在不编辑任何库代码的情况下执行此操作
If possible, I'd like to do this without editing any library code
截至今天,org.json
库版本 20170516
提供了 accumulate()
方法将重复的键条目存储到 JSONArray
As of today the org.json
library version 20170516
provides accumulate()
method that stores the duplicate key entries into JSONArray
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("a", "b");
jsonObject.accumulate("c", "d");
jsonObject.accumulate("c", "e");
jsonObject.accumulate("f", "g");
System.out.println(jsonObject);
输出:
{
"a":"b",
"c":["d","e"],
"f":"g"
}