0

This might be a very silly one but I'd like to know how I can create a json file that looks like this:

{
  "aString":"foo",
  "anArray":
  [
    "foo",
    "bar",
    "obj"
  ],
  "anInteger":100
}

instead of this: {"aString":"foo","anArray":["foo","bar","obj"],"anInteger":100}

Here's the code that creates the second one:

public class Main
{
    public static final String defDir = "C:\\Users\\*UserName*\\Desktop\\Java\\Test\\src\\Files\\";

    public static void main(String[] args) {

        JSONObject obj = new JSONObject();
        obj.put("aString", "foo");
        obj.put("anInteger", 100);

        JSONArray list = new JSONArray();
        list.add("foo");
        list.add("bar");
        list.add("obj");

        obj.put("anArray", list);

        try (FileWriter file = new FileWriter(defDir + "test.json"))
        {
            file.write(obj.toString());
            file.flush();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

And how do I read multiple-line json with JSON.simple

Keheck
  • 131
  • 1
  • 10

1 Answers1

0

You can just use obj.toString(4) to indent with 4 spaces for example. JSONObject has a overloaded toString() method which accepts indent parameter which in turn pretty print the JSON.

From the Javadocs. Here I am quoting for your reference.

public java.lang.String toString(int indentFactor) throws JSONException

Make a prettyprinted JSON text of this JSONObject. Warning: This method assumes that the data structure is acyclical.

Parameters:

indentFactor - The number of spaces to add to each level of indentation.

Returns: a printable, displayable, portable, transmittable representation of the object, beginning with { (left brace) and ending with } (right brace).

Pradeep Simha
  • 17,683
  • 18
  • 56
  • 107