简体   繁体   English

如何将JSON文件加载到每个记录具有唯一名称的Java中?

[英]How to load a JSON file into java that has unique name for each record?

For example my JSON file look like this; 例如,我的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"
 }

 ...
 ...
}

This would have been simple if the file only contained a few records, but in my case I'm dealing with thousands of records. 如果该文件仅包含几条记录,这本来就很简单,但就我而言,我正在处理成千上万条记录。 For simpler version I've used gson library but not sure how I could load this JSON file which has unique name for each record into Java. 对于更简单的版本,我使用了gson库,但是不确定如何将具有每个记录唯一名称的JSON文件加载到Java中。

***************UPDATE******************************* ***************更新***********************************

I now managed to read it raw and Map the data. 现在,我设法将其原始读取并映射数据。 However, still have a minor issue. 但是,仍然有一个小问题。

This is the code I used to Map 这是我用来映射的代码

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"));

I'm getting below results, which is fine. 我得到了低于结果的结果,这很好。 However, not sure how I could obtain the data within "values" of the map. 但是,不确定如何获取地图“值”内的数据。

{A={}, B=1, C=2, D=3} {A = {},B = 1,C = 2,D = 3}

I tried below to re-map but it's failing as expected, because the keys no longer are surrounded by double quotes (see above)! 我在下面尝试重新映射,但是按预期失败了,因为键不再被双引号包围了(见上文)!

Map<String, Object> nestedObject = mapper.readValue(
                mapObject.get("Test1").toString(),
                new TypeReference<Map<String, Object>>() {
                });

If you know your objects all contain the same keys A, B, C and D then you could create a class that maps a single object 如果你知道你的对象都含有相同的密钥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;
}

and then unmarshal the JSON as a Map<String, MyEntry> 然后将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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM