我已经使用gson的JsonWriter编写了一个程序来创建一个json文件,创建json文件效果很好但它给了我格式化的json不是最好的看到我希望能够手工编辑这个文件
示例:程序给了我
{"bells":{"category":"hostile","sounds":["bells"]},"ankylosaurus":{"category":"hostile","sounds":["dinosaurs/ankylosaurus/AnkylosaurusCall1","dinosaurs/ankylosaurus/AnkylosaurusCall2","dinosaurs/ankylosaurus/AnkylosaurusRoar1","dinosaurs/ankylosaurus/AnkylosaurusRoar2","dinosaurs/ankylosaurus/AnkylosaurusSay1","dinosaurs/ankylosaurus/AnkylosaurusSay2"]},...
但我想将其导出为
{
"bells":{
"category":"hostile",
"sounds":[
"bells"
]
},
"ankylosaurus":{
"category":"hostile",
"sounds":[
"dinosaurs/ankylosaurus/AnkylosaurusCall1",
"dinosaurs/ankylosaurus/AnkylosaurusCall2",
"dinosaurs/ankylosaurus/AnkylosaurusRoar1",
"dinosaurs/ankylosaurus/AnkylosaurusRoar2",
"dinosaurs/ankylosaurus/AnkylosaurusSay1",
"dinosaurs/ankylosaurus/AnkylosaurusSay2"
]
},
...
答案 0 :(得分:0)
Gson
比JsonWriter
更通用,并且具有“漂亮打印”选项。
您可以使用它来写入这样的流:
private Gson gson = new GsonBuilder()
.setPrettyPrinting()
.create();
OutputStreamWriter writer = ...
writer.write(gson.toJson(object));
答案 1 :(得分:0)
是的!启用漂亮打印:)
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(yourDataHere);
答案 2 :(得分:0)
如果您想继续使用JsonWriter
,specify an indent可以实现您的目标:
jsonWriter.setIndent(" ");