如果有很多二级字段,如何解析嵌套的 json 文件?

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

我试图用 gson 解析一个 json 文件,我找到了多个解决方案。但我的问题是,我有很多领域?将它们全部写在 class 中。如何在不使用 name1 - name564 创建 class 的情况下获取车内信息 + 颜色? 这是一个例子 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}
        }
    }
}

我不确定我是否完全理解了问题,但如果我理解了,解决方案可能是创建一个新的 Java class,命名为 MyClass。 MyClass 将 Name1, ..., Name564 作为实例,将数字、颜色、汽车作为属性,如下所示:

class MyClass {
    private String name;
    private int number; //use int or String if you prefer
    private String color; //you can also use enum instead
    private Map<String, Integer> cars;

    public MyClass(String name) {
        this.name = name;
        cars = new HashMap<>(); // or any other map implementation, depending on the needs
    }

    public void addCar(String model, int numCars) {
        cars.put(model, numCars); // if you always want to replace, add any necessary checks before that
    }

    //or you can use setCars, seeing test.get("cars") as Map
    public void setCars(Map<String,Integer> cars) {
        this.cars = cars;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    public void setColor(String color) {
        this.color = color;
    }
}

然后,当您迭代 json 文档时,您可以设置遇到的字段。对于您遇到的每个 "Name" 元素,您可以创建一个新的 MyClass 实例:MyClass currItem = new MyClass("Name"+counter),其中 counter 是一个计数器,您从 1 初始化到 [=27= 的子元素的大小] 元素。

doc.get("test").get("Name"+counter) 会给你下一个项目。您可以对相应的字段使用 .get("color").get("number").get("cars")

希望对您有所帮助。

您可以使用 Map 进行映射。下面是解析示例的代码:

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