例如我的JSON文件看起来像这样;
{
"Test1": {
"A": {},
"B": "1",
"C": "2",
"D": "3"
},
"Test2": {
"A": {},
"B": "4",
"C": "5",
"D": "6"
},
"Test3": {
"A": {},
"B": "7",
"C": "8",
"D": "9"
},
"Test4": {
"A": {},
"B": "10",
"C": "11",
"D": "12"
}
...
...
}
如果文件只包含一些记录,这将很简单,但在我的情况下,我正在处理数千条记录。对于更简单的版本,我使用了gson库,但不确定如何将每个记录具有唯一名称的JSON文件加载到Java中。
*************** UPDATE *******************************
我现在设法读取原始数据并映射数据。但是,仍有一个小问题。
这是我用来映射的代码
ObjectMapper mapper = new ObjectMapper();
File jsonFile = new File(jsonFilePath);
Map<String, Object> mapObject = mapper.readValue(jsonFile,
new TypeReference<Map<String, Object>>() {
});
System.out.println(mapObject.get("Test1"));
我的结果低于结果,这很好。但是,不确定如何在地图的“值”内获取数据。
{A = {},B = 1,C = 2,D = 3}
我在下面尝试重新映射但是它按预期失败了,因为键不再被双引号括起来(见上文)!
Map<String, Object> nestedObject = mapper.readValue(
mapObject.get("Test1").toString(),
new TypeReference<Map<String, Object>>() {
});
答案 0 :(得分:0)
如果您知道您的对象都包含相同的键A,B,C和D,那么您可以创建一个映射单个对象的类
class MyEntry {
/**
* You've tagged the question "gson" but your example code uses Jackson so I've
* written this class with Jackson annotations rather than Gson ones.
*/
@JsonProperty("A")
public Object a; // or a more specific type if you know one
@JsonProperty("B")
public String b;
@JsonProperty("C")
public String c;
@JsonProperty("D")
public String d;
}
然后将JSON解组为Map<String, MyEntry>
Map<String, MyEntry> mapObject = mapper.readValue(jsonFile,
new TypeReference<Map<String, MyEntry>>() {
});
System.out.println(mapObject.get("Test1").b); // prints 1