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"
}
}