简体   繁体   中英

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

For example my JSON file look like this;

{
  "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.

***************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}

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

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>

Map<String, MyEntry> mapObject = mapper.readValue(jsonFile,
    new TypeReference<Map<String, MyEntry>>() {
    });

System.out.println(mapObject.get("Test1").b); // prints 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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