我们正在读取文件更改内容并写回相同的位置。
java - 如何在java/only特定属性中对JSON数组应用缩进?
源代码:
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();
}
我们有什么:
{
"array": ["element 1","element 2","element 3" ],
"object": {
"property1": "value1",
"property2":"value2"
}
}
生成的代码:
{
"array": [
"element 1",
"element 2",
"element 3"
],
"object": {
"property1": "value1",
"property2": "value2"
}
}
我们需要的
{
"array": ["element 1","element 2","element 3" ],
"object": {
"property1": "value1",
"property2":"value2"
}
}