0

I want to create multiple arrays at the run-time, moreover the program have ability to add the data to the particular array called upon.

 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);
            }
        }

    });

I have tried above and it is creating the json array and also adding the elements to the called array but only for once, but I want to create a new array whenever user want to add new productType. Json output achieved:

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

Json output required:

{"Insight":[{"year":"2019","model":"myc"},{"year":"2018","model":"ii"}], "Odyssey":[{"year":"2019","model":"ody"}],"Coupe":[{"year":"2019","model":"cup"},{"year":"2017","model":"cup"}]}
4
  • Do you know the Gson library (github.com/google/gson/blob/master/UserGuide.md) from Google? If not, it is worth to read the documentation. Makes life easier if you have to work with JSON. Commented Mar 13, 2019 at 20:30
  • Iam using simple json Commented Mar 13, 2019 at 20:30
  • SimpleJson ist not maintained anymore since five years (github.com/fangyidong/json-simple). Think about using Gson if possible. Commented Mar 13, 2019 at 21:02
  • seriously i will go through GSon , as simple json always makes me in trouble. Thanks Commented Mar 14, 2019 at 3:55

3 Answers 3

1

You should write back root JSON node. Name of your root object is jsonObject but you write jo. Take a look on below example:

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Michał Ziober for the required solution
1

Since you are reading the entire file into memory, I'm assuming you have enough memory to store all the data you intend on storing. With that assumption, I think a better and more efficient approach would be to have something like

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

Then, for each item that gets added:

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

This will save you the need to read in the file in order to add items, and you can just use the file storage as persistence

1 Comment

Its works wonderfully with minimum efforts of reading the file, but for the very first time I have to read the file if there exist no data. Though I dont know more about the persistence but seems it is worth using when doing filing and storage. Thank You aaarbor
0

Try this:

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();
}

}

The output file looks like this

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

1 Comment

Thanks , its not what i was looking for, but I got the solution from others responses. thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.