我可以将gson JsonWriter格式化为可读的东西吗?

时间:2015-01-27 12:19:55

标签: java json format gson

我已经使用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"
    ]
},
...

3 个答案:

答案 0 :(得分:0)

GsonJsonWriter更通用,并且具有“漂亮打印”选项。

您可以使用它来写入这样的流:

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)

如果您想继续使用JsonWriterspecify an indent可以实现您的目标:

jsonWriter.setIndent("    ");