java - 如何在运行时创建 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"}]}
解决方案
由于您正在将整个文件读入内存,我假设您有足够的内存来存储您打算存储的所有数据。有了这个假设,我认为更好,更有效的方法是拥有类似的东西
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
这将节省您读取文件以添加项目的需要,并且您可以将文件存储用作持久性
推荐阅读
- javascript - 如何使用 github 作为我的服务器使用 firebase admin SDK
- jquery - 单击功能在 div 内部不起作用,但在外部起作用
- c# - 如何在 Windows 10 桌面应用程序中隐藏 WPF 中的任务栏?
- java - 如何选择其值大于零的元素
- python - 带有无效 URL 的 python requests.get
- arrays - C. 函数中的 malloc() 和 free() 不起作用
- sql - sql中的程序将10条记录插入表中
- apache-spark - 使用 spark 根据列值的总和将数据集分为 2
- python - Google colab gpu 执行代码耗时过长
- python - Python 是否有像 Mathematica 这样的“嵌套”函数?