How to write a JSONObject to a file, which has JSONArray inside it, in Java?

alena_fox_spb picture alena_fox_spb · Oct 6, 2013 · Viewed 45.1k times · Source

I have JSON file, that I need to read, edit and write out again.

Reading works fine, I struggle with the write part of the JSON Array in my data.

I use JSON.simple library to work with JSON in Java.

The file looks like this:

{
    "maxUsers":100,
    "maxTextLength":2000,
    "maxFileSize":2000,
    "services":
    [
        {
            "serviceName":"Яндекc",
            "className":"YandexConnector.class",
            "isEnabled":true
        },

        {
            "serviceName":"Google",
            "className":"GoogleConnector.class",
            "isEnabled":false
        }
    ]
}

When I try to write JSON-data (variable obj) to file, the services array is broken. My writing code:

JSONObject obj = new JSONObject();
obj.put("maxUsers", this.getMaxUsers());
obj.put("maxTextLength", this.getMaxTextLength());
obj.put("maxFileSize", this.getMaxFileSize()); 

JSONArray servicesJSON = new JSONArray();
ArrayList<Service> servicesArray = this.getServices();
for(int i=0; i< servicesArray.size(); i++)
{
    servicesJSON.add(servicesArray.get(i));
}
obj.put("services", servicesJSON);


FileWriter file = new FileWriter(filename);                
obj.writeJSONString(file);
file.flush();
file.close();

This outputs:

{
    "services":
    [
        translator.settings.Service@121c5df,
        translator.settings.Service@45f4ae
    ],
    "maxTextLength":2000,
    "maxUsers":100,
    "maxFileSize":2000
}

How can I write the JSON data correctly to a file, if I have it in a JSONArray like services ?


The code, where I read the JSON data from the file (that works fine):

JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader(filename));
JSONObject jsonObject = (JSONObject) obj;

setMaxUsers((Long) jsonObject.get("maxUsers"));
setMaxTextLength((Long) jsonObject.get("maxTextLength"));
setMaxFileSize((Long) jsonObject.get("maxFileSize"));
// get all list of services
JSONArray serv = (JSONArray) jsonObject.get("services");

for (int i = 0; i < serv.size(); i++) {
    JSONObject service = (JSONObject) serv.get(i);
    Service servec = new Service();
    servec.setServiceName((String) service.get("serviceName"));
    servec.setClassName((String) service.get("className"));
    servec.setIsEnabled((Boolean) service.get("isEnabled"));

    services.add(i, servec);
}

The editing part is not yet written, so I call the writing part directly after the reading.


Answer

Angelo Fuchs picture Angelo Fuchs · Oct 6, 2013

Have a look at the examples of JSON-simple.

It says here that you need to put the Objects one by one into the Array, using only primitive and String values. You may use Collections like Map that by themselves only contain String or primitive values.

  JSONArray list = new JSONArray();
  list.add("foo");
  list.add(new Integer(100));
  list.add(new Double(1000.21));
  list.add(new Boolean(true));
  list.add(null);
  StringWriter out = new StringWriter();
  list.writeJSONString(out);

So, adding your Services is not allowed and won't work. You should add a toMap method in it where you convert it to a Map and fromMap to convert it back.

Like this (in Services.java):

 public Map toMap() {
     HashMap<String, String> serviceAsMap = new HashMap<>();
     servicesAsMap.put("serviceName", serviceName);
     servicesAsMap.put("className", this.class.getName() + ".class");
     servicesAsMap.put("isEnabled", isEnabled);
     // ... continue for all values
     return servicesAsMap;
 }

then you can use that Map to populate your JSONArray like this:

        JSONArray servicesJSON = new JSONArray();
        ArrayList<Service> servicesArray = this.getServices();
        for(int i=0; i< servicesArray.size(); i++)
        {
            servicesJSON.add(servicesArray.get(i).toMap()); // use the toMap method here.
        }
        obj.put("services", servicesJSON);