Java – How do I parse nested json files if I have a lot of secondary fields?

How do I parse nested json files if I have a lot of secondary fields?… here is a solution to the problem.

How do I parse nested json files if I have a lot of secondary fields?

I

tried to parse a json file with gson and I found multiple solutions. But my question is, I have a lot of areas? Actually write them all inside the class. How do I get the information inside the car + color without creating a class with name1 – name564?
Here is an example json: ́

{"test":
    {"Name1":
        {"number":"123",
        "color":"red",
        "cars":{"BMW":1,
            "PORSCHE":2,
            "MERCEDES":4,
            "FORD":6}
        },
    .
    .
    .
    .
    .
    .
    "Name564":
        {"number":"143",
        "color":"blue",
        "cars":{"BMW":9,
                "PORSCHE":2,
                "MERCEDES":3,
                "FORD":7}
        }
    }
}

Solution

You can use maps for mapping. Here’s the code to parse the example:

class JsonRoot {
    Map<String, JsonName> test;
}

class JsonName {
    String number;
    String color;
    Map<String, Integer> cars;
}

...
JsonRoot jsonRoot;
Gson gson = new Gson();
try (BufferedReader reader = Files.newBufferedReader(Paths.get("test.json"))) {
    jsonRoot = gson.fromJson(reader, JsonRoot.class);
}

Related Problems and Solutions