我正面临这个json的麻烦。
{"1234345": [{
"queue": "XXX",
"name": "XXXXX",
"entries": [{
"points": 54,
"isInactive": false,
}],
"tier": "ASDF"
}]}
但它也可以有这样的形状:
{
"1234345": [{
"queue": "XXX",
"name": "XXXXX",
"entries": [{
"points": 54,
"isInactive": false,
}],
"tier": "ASDF"
}],
"22683144": [{
"queue": "XXX",
"name": "XXXXX",
"entries": [{
"points": 54,
"isInactive": false,
}],
"tier": "ASDF"
}]
}
根密钥是一个数组,它可以在每次调用服务时更改。因此它的动态。
我生气了。我听说使用动态键的最佳选择是使用Map。但在这种情况下,我如何命名将包含该地图的属性?在这种情况下是一个数组我不知道它应该是一个地图或如何创建相应的POJO。有什么帮助吗?
首先,我要做的是为条目创建一个类。
public class myEntry {
public String points;
public String isInactive;
}
然后是它的容器类。
public class myObject {
public String queue;
public String name,
public myEntry[] entries;
public String tier;
}
但我被困在这里,我不知道如何继续。
答案 0 :(得分:2)
您始终可以使用Map
。考虑一下您在问题中发布的JSON:
{
"1234345": [
{
"queue": "XXX",
"name": "XXXXX",
"entries": [
{
"points": 54,
"isInactive": false
}
],
"tier": "ASDF"
}
],
"22683144": [
{
"queue": "XXX",
"name": "XXXXX",
"entries": [
{
"points": 54,
"isInactive": false
}
],
"tier": "ASDF"
}
]
}
使用Jackson,一种流行的Java JSON解析器,可以将其解析为Map<String,Object>
对象:
String json = "{\"1234345\":[{\"queue\":\"XXX\",\"name\":\"XXXXX\",\"entries\":["
+ "{\"points\":54,\"isInactive\":false}],\"tier\":\"ASDF\"}],"
+ "\"22683144\":[{\"queue\":\"XXX\",\"name\":\"XXXXX\",\"entries\":["
+ "{\"points\":54,\"isInactive\":false}],\"tier\":\"ASDF\"}]}";
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map =
mapper.readValue(json, new TypeReference<Map<String, Object>>() {});
您可以使用POJO代替Object
:
public class Foo {
private String queue;
private String name;
private String tier;
private List<Bar> entries;
// Getters and setters omitted
}
public class Bar {
private Integer points;
private Boolean isInactive;
// Getters and setters omitted
}
使用杰克逊,您的代码就像:
String json = "{\"1234345\":[{\"queue\":\"XXX\",\"name\":\"XXXXX\",\"entries\":["
+ "{\"points\":54,\"isInactive\":false}],\"tier\":\"ASDF\"}],"
+ "\"22683144\":[{\"queue\":\"XXX\",\"name\":\"XXXXX\",\"entries\":["
+ "{\"points\":54,\"isInactive\":false}],\"tier\":\"ASDF\"}]}";
ObjectMapper mapper = new ObjectMapper();
Map<String, List<Foo>> map =
mapper.readValue(json, new TypeReference<Map<String, List<Foo>>>() {});