Why will Gson pretty-print to the console, but not the file?

后端 未结 1 1831
天命终不由人
天命终不由人 2021-01-16 18:38

I have a class, let\'s call it Cls, with some values in it. When I use a Gson instance declared with GsonBuilder.setPrettyPrinting().create() and use that to se

1条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-16 19:10

    Presumably, you're using something like this

    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    
    try (FileWriter fileWriter = ...) {
        gson.toJson(new Example(), Example.class, new JsonWriter(fileWriter));
    }
    

    The JsonWriter wasn't created from the Gson object and is therefore not configured to pretty print. You can, instead, retrieve a JsonWriter instance from the Gson object with newJsonWriter

    gson.toJson(new Example(), Example.class, gson.newJsonWriter(fileWriter));
    

    which

    Returns a new JSON writer configured for the settings on this Gson instance.

    This instance will pretty-print.

    You can also set the indent on your own instance

    JsonWriter jsonWriter = new JsonWriter(fileWriter);
    jsonWriter.setIndent("  ");
    gson.toJson(new Example(), Example.class, jsonWriter);
    

    0 讨论(0)
提交回复
热议问题