所以,我已经做了一段时间的GSON,但我刚刚遇到了使用JSON Maps的问题,据我所知它基本上只是Key Value对,他的值是JSON对象。
为了让你知道我来自哪里,这是我的JSON
{
"configs":[
{
"com.hp.sdn.adm.alert.impl.AlertManager":{
"trim.alert.age":{
"def_val":"14",
"desc":"Days an alert remains in storage (1 - 31)",
"val":"14"
},
"trim.enabled":{
"def_val":"true",
"desc":"Allow trim operation (true/false)",
"val":"true"
},
"trim.frequency":{
"def_val":"24",
"desc":"Frequency in hours of trim operations (8 - 168)",
"val":"24"
}
}
},
{
"com.hp.sdn.adm.auditlog.impl.AuditLogManager":{
"trim.auditlog.age":{
"def_val":"365",
"desc":"Days an audit log remains in storage (31 - 1870)",
"val":"365"
},
"trim.enabled":{
"def_val":"true",
"desc":"Allow trim operation (true/false)",
"val":"true"
},
"trim.frequency":{
"def_val":"24",
"desc":"Frequency in hours of trim operations (8 - 168)",
"val":"24"
}
}
}
]
}
所有这些com.hp.sdn ......都是动态的,因为在运行时之前我不会知道密钥名称。我想我可以使用一个HashMap,而GSON会想出来,但我不确定我会说出这个字段......
这是我到目前为止的课程
package com.wicomb.sdn.models.configs;
import java.util.HashMap;
import com.wicomb.sdn.types.Model;
public class ConfigResponse extends Model {
private ConfigGroup[] configs;
}
package com.wicomb.sdn.models.configs;
import com.wicomb.sdn.types.Model;
public class ConfigGroup extends Model {
private HashMap<String,Config> ????;
}
TL; DR我应该如何编写Java类让Gson知道如何处理我不知道名字的Json属性..还有很多。
答案 0 :(得分:1)
您可以使用HashMap
(或者如果子订单的重要性为LinkedHashMap
)向Gson提供,而不是像对任何其他地图一样迭代条目或键。
在下面的代码中,我使用以下json作为输入:
{
"test": 123,
"nested":{
"nested-1": 1,
"nested-2": 2
}
}
代码如下:
public void testGson() {
String input = "{\"test\": 123, \"nested\": {\"nested-1\": 1, \"nested-2\": 2}}";
LinkedHashMap<String, Object> json = new Gson().fromJson(input, LinkedHashMap.class);
// iterating
for(Map.Entry<String, Object> entry : json.entrySet()){
System.out.println(entry.getKey() + " -> " + entry.getValue());
}
// testing values
System.out.println(json.get("test")); // should be 123
Map<String, Object> nested = (Map<String, Object>) json.get("nested");
System.out.println(nested.get("nested-1")); // should be 1
System.out.println(nested.get("nested-2")); // should be 2
}