Jose Ramon
Jose Ramon

Reputation: 5438

Store information into Json file in java

I am using JSONObject library in order to store data in json file from my java code. I came across the following tutorial about JSONObject. What I am trying to figure out is how the Json hierarchy could work. Basically I want to store in a json file all the X and Y mouse events and the correspondant timestamps. I have the following code:

Jobj = new JSONObject();
Jobj.put("user interactions", "Learning game applications"); 
EventHandler<MouseEvent> handler = event -> {
        event.getSceneX();
        event.getSceneY();
        java.util.Date date = new java.util.Date();

        JSONArray list = new JSONArray();
        list.add(new Timestamp(date.getTime()));
        list.add(event.getSceneX());
        list.add(event.getSceneY());
        Jobj.put("Mouse Events", list);

    };

When I am trying to store this Json object into file I got just only one (X, Y, Time). How can I got all of them?

{"Mouse Events":[2016-11-02 14:49:07.1,457.0,642.0],"user interactions":"Learning game applications"}

Upvotes: 0

Views: 92

Answers (1)

neuhaus
neuhaus

Reputation: 4094

You are storing the array in an object "Mouse Events". Every time you reach the line

Jobj.put("Mouse Events", list);

the previous entry is overwritten. What you want is to have an array "Mouse events" and add new arrays to the array on every event.

Retrieve the value as a JSONArray, add() the new JSONArray to the array you retrieved, then store it again in Jobj.

Upvotes: 2

Related Questions