1

The JSON example file consists of:

{
    "1st_key": "value1",
    "2nd_key": "value2",
    "object_keys": {
        "obj_1st": "value1",
        "obj_2nd": "value2",
        "obj_3rd": "value3",
    }
}

I read the JSON file into a String with this StringBuilder method, in order to add the newlines into the string itself. So the String looks exactly like the JSON file above.

public String getJsonContent(String fileName) {       
        StringBuilder result = new StringBuilder("");
        File file = new File(fileName);
        try (Scanner scanner = new Scanner(file)) {
              while (scanner.hasNextLine()) {
                    String line = scanner.nextLine();
                    result.append(line).append("\n");
              }
              scanner.close();
        } catch (IOException e) {
              e.printStackTrace();
        }
        return result.toString();     
    }

Then I translate the JSON file into an Object using MongoDB API (with DBObject, BasicDBObject and util.JSON) and I call out the Object section I need to change, which is 'object_keys':

File jsonFile = new File(C:\\example.json);
String jsonString = getJsonContent(jsonFile.getAbsolutePath());
DBObject jsonObject = (DBObject)JSON.parse(jsonString);
BasicDBObject objectKeys = (BasicDBObject) jsonObject.get("object_keys");

Now I can write new values into the Object using the PUT method like this:

objectKeys.put("obj_1st","NEW_VALUE1");
objectKeys.put("obj_2nd","NEW_VALUE2");
objectKeys.put("obj_3rd","NEW_VALUE3");

! This following part not needed, check out my answer below.

After I have changed the object, I need to write it back into the json file, so I need to translate the Object into a String. There are two methods to do this, either one works.

  String newJSON = jsonObject.toString();
or
  String newJSON = JSON.serialize(jsonObject);

Then I write the content back into the file using PrintWriter

PrintWriter writer = new PrintWriter(C:\\example.json)
writer.print(newJSON);
writer.close();

The problem I am facing now is that the String that is written is in a single line with no formatting whatosever. Somewhere along the way it lost all the newlines. So it basically looks like this:

{"1st_key": "value1","2nd_key": "value2","object_keys": { "obj_1st": "NEW_VALUE1","obj_2nd": "NEW_VALUE2","obj_3rd": "NEW_VALUE3", }}

I need to write the JSON file back in the same format as shown in the beginning, keeping all the tabulation, spaces etc.

Is this possible somehow ?

Ecorin
  • 11
  • 1
  • 4

3 Answers3

1

When you want something formatted the way you said it is addressed as writing to a file in a pretty/beautiful way. For example: Output beautiful json. A quick search on google found what i believe to solve your problem.

Solution

Rafael Saraiva
  • 908
  • 2
  • 11
  • 23
0

You're going to have to use a json parser of some sort. I personally prefer org.json and would recommend it if you are manipulating the json data, but you may also like json-io which is really good for json serialization with no external dependencies.

With json-io, it's as simple as

String formattedJson = JsonWriter.formatJson(jsonObject.toString())

With org.json, you simply pass an int to the toString method.

Tommy
  • 580
  • 4
  • 7
0

Thanks Saraiva, I found a surprisingly simple solution by Googling around with the words 'pretty printing JSON' and used the Google GSON library. I downloaded the .jar and added it to my project in Eclipse.

These are the new imports I needed:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

Since I already had the JSON Object (jsonObject) readily available from my previous code, I only needed to add two new lines:

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String newJSON = gson.toJson(jsonObject);

Now when I use writer.print(newJSON); it will write the JSON in the right format, beautifully formatted and indented.

Ecorin
  • 11
  • 1
  • 4