How to parse a nested json file if there are to many secondlevel-fields?

Umikron :

I am trying to parse a json file with gson and i found multiple solutions. But my problem is, that i have to many fields? to actually write them all down in a class. How can i get the information inside cars + the 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}
        }
    }
}
vbezhenar :

You can use Map for mappings. Here's code to parse your 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);
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=20007&siteId=1