首页 > 解决方案 > 如何在运行时创建 json 数组并将元素添加到特定数组?

问题描述

我想在运行时创建多个数组,而且程序能够将数据添加到调用的特定数组中。

 button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            try {

                String productType = txtProductType.getText();
                String model = txtModel.getText();
                String year = txtYear.getText();

                File file1 = new File(FILE_NAME);
                if (file1.length() == 0) {

                    JSONObject jsonObject = new JSONObject();

                    map = new LinkedHashMap(2);

                    map.put("model", model);
                    map.put("year", year);

                    jsonArray.add(map);

                    jsonObject.put(productType, jsonArray);

                    FileWriter file = new FileWriter(FILE_NAME, false);
                    file.append(jsonObject.toString());
                    file.flush();
                    file.close();

                } else {
                    JSONParser parser = new JSONParser();
                    Object obj = parser.parse(new FileReader(FILE_NAME));
                    if (obj == null) {
                        System.out.println("ex");
                    }
                    JSONObject jsonObject = (JSONObject) obj;
                    JSONArray jsonArray = (JSONArray) jsonObject.get(productType);

                    JSONObject jo = new JSONObject();

                    map = new LinkedHashMap(2);
                    map.put("model", model);
                    map.put("year", year);
                    jsonArray.add(map);

                    jo.put(productType, jsonArray);

                    FileWriter file = new FileWriter(FILE_NAME, false);
                    file.append(jo.toString());
                    file.flush();
                    file.close();

                }

                JOptionPane.showMessageDialog(f, "Data parsed into JSON.", "Message", JOptionPane.PLAIN_MESSAGE);
            } catch (Exception ex) {
                Logger.getLogger(WriteInJSONGUI.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    });

我在上面尝试过,它正在创建 json 数组并将元素添加到被调用的数组中,但只是一次,但我想在用户想要添加新的 productType 时创建一个新数组。实现的 Json 输出:

{"Insight":[{"year":"2019","model":"myc"},{"year":"dgdfg","model":"ii"}]}

需要 Json 输出:

{"Insight":[{"year":"2019","model":"myc"},{"year":"2018","model":"ii"}], "Odyssey":[{"year":"2019","model":"ody"}],"Coupe":[{"year":"2019","model":"cup"},{"year":"2017","model":"cup"}]}

标签: javaarraysjson

解决方案


由于您正在将整个文件读入内存,我假设您有足够的内存来存储您打算存储的所有数据。有了这个假设,我认为更好,更有效的方法是拥有类似的东西

Map<String, List<Map<String,String>>> items = new HashMap<>();

然后,对于添加的每个项目:

List<Map<String,String>> list = items.computeIfAbsent(productType, k-> new ArrayList<>());
Map<String,String> newMap = new HashMap<>();
newMap.put("model", model)
newMap.put("year", year);
list.add(newMap);
// convert list to json string and write to file in overwrite mode

这将节省您读取文件以添加项目的需要,并且您可以将文件存储用作持久性


推荐阅读