How to apply Indent to array json in java

636 views Asked by At

We are reading the file changing the content and writing back to the same location.

How to apply indentation to a JSON array in java/only specific properties?

Source code:

import com.google.gson.JsonElement;
import com.google.gson.internal.Streams;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;

String file="D:\\Documents\\read.json";     
JsonElement root = Streams.parse(new JsonReader(new FileReader(file)));
// changing the json values here
try (Writer writer = new FileWriter(file)) {
    JsonWriter jsonWriter = new JsonWriter(writer);
    jsonWriter.setIndent("\t");
    Streams.write(root, jsonWriter);
    jsonWriter.flush();
}  catch (IOException ioe) {
    ioe.printStackTrace();
}

What we have:

{
  "array": ["element 1","element 2","element 3" ],
  "object": {
    "property1": "value1",
    "property2":"value2"
  }
}

Code generated:

{
    "array": [
        "element 1",
        "element 2",
        "element 3"
    ],
    "object": {
        "property1": "value1",
        "property2": "value2"
    }
}

What we need

{
  "array": ["element 1","element 2","element 3" ],
  "object": {
    "property1": "value1",
    "property2":"value2"
  }
}
1

There are 1 answers

2
EricSchaefer On

The usual JSON serializers don't offer selective indentation. Most offer "pretty-printing" (generating output that is not all on one line) targeted at human readers. In general this is not even needed, as the different outputs are sematically equal and JSON is meant for machines to read/write and machines do not care about indentation. Pretty-printing is only supported as a convenience in case a human needs to debug it.

The only solution I can offer is to write your own serializer, but this is not as easy as it might seem, except for the most simple cases.