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

时间:2019-03-13 20:01:58

标签: java arrays 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"}]}

3 个答案:

答案 0 :(得分:1)

由于您正在将整个文件读取到内存中,因此我假设您有足够的内存来存储要存储的所有数据。有了这个假设,我认为一种更好,更有效的方法就是拥有类似的东西

withConfirm(true) { $("Element responsible for download").click() } 

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

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

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

答案 1 :(得分:1)

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

答案 2 :(得分:0)

尝试一下:

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