如何在运行时创建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"}]}

您应该写回root JSON节点。根对象的名称是jsonObject,但您编写jo。请看以下示例:

JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader(jsonFile));
// root object
JSONObject root = (JSONObject) obj;
JSONArray jsonArray = (JSONArray) root.get(productType);
if (jsonArray == null) {
    jsonArray = new JSONArray();
}
Map<String, Object> map = new LinkedHashMap<>(2);
map.put("model", "Model");
map.put("year", 2019);
jsonArray.add(map);
root.put(productType, jsonArray);
FileWriter file = new FileWriter(jsonFile, false);
// use root object
file.append(root.toString());
file.flush();
file.close();

由于您将整个文件读为内存,因此我假设您有足够的内存来存储您打算存储的所有数据。有了这个假设,我认为一种更好,更有效的方法就是拥有

之类的东西
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

这将节省您需要在文件中读取以添加项目的需要,并且您可以将文件存储使用为persistence

尝试以下:

public class Main {
public static void main(String[] args) throws IOException {
    List jsonArray = new ArrayList();
    for (int i = 0; i < 5; i++) {
        add(jsonArray);
    }
}
private static void add(List jsonArray) throws IOException {
    JSONObject jsonObject = new JSONObject();
    LinkedHashMap<Object, Object> map = new LinkedHashMap<>(2);
    map.put("model", "myc");
    map.put("year", "2019");
    jsonArray.add(map);
    jsonObject.put("Insight", jsonArray);
    FileWriter file = new FileWriter("test.json", false);
    file.append(jsonObject.toString());
    file.flush();
    file.close();
}

}

输出文件看起来像

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

最新更新