我的程序必须输出以下 JSON 格式:
{ "success": {
"code": 1,
"desc": "success" },
"response": {
"res1": [
{
"Item": "item1",
"Description": [
{
"desc": "ad1",
"active": true,
"details": [
{
"Type": "Type1",
"Count": 2,
"Status": true
},
{
"Type": "TYpe2",
"Count": 3,
"Status": false
},
]
},
{
"desc": "item2",
"active": true,
"details": [
{
"Type": "Type1",
"Count": 4,
"Active": true
}
]
},
{
"Item": "item2",
"Description": [
{
"desc": "d2",
"Active": true,
"details": [
{
"Type": "Type3",
"Count": 6,
"Active": true
},
]
},
]
}
]
}
}
我编写了以下内容来创建此 json 格式
HashMap<String, HashMap<String, String>> m1 = new HashMap<String, HashMap<String, String>>();
HashMap<String, String> m2 = new HashMap<String, String>();
HashMap<String, ArrayList<HashMap<String, String>>> m3 = new HashMap<String, ArrayList<HashMap<String, String>>>();
为了创建指定的 JSON 格式,我尝试将 m3 和 m2 放入 m1 中。但由于它们不是同一类型,因此不允许放置。
我正在使用 GSON 将集合转换为 JSON。
Gson gson = new Gson();
String json1 = gson.toJson(m1);
我的问题是:为了创建 JSON 格式,我必须使用 Java 中的哪个集合?
最佳答案
处理此类复杂 JSON 结构的最佳方法是创建一个具有相同结构的类,并具有将底层数组表示为列表的属性。然后,您可以使用gson以简单的方式将对象转换为 JSON。
换句话说,不要尝试将结构放入复杂集合或现有 Java 类的组合中,而是创建一个精确表示数据的类,填充它,然后将其转换为 JSON。
关于Java 集合到 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38009818/