繁体   English   中英

如何在运行时创建json数组并将元素添加到特定数组?

[英]how to create json array at run-time and add elements to the particular array?

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

 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

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

你应该写回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();

尝试这个:

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"}]}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM