将具有重复键的 JSON 对象转换为 JSON 数组 [英] Convert JSON object with duplicate keys to JSON array

查看:36
本文介绍了将具有重复键的 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"  
}

这篇关于将具有重复键的 JSON 对象转换为 JSON 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆