-1

I have a String formatted as a JSON (with pretty print) that I would like to create a new JSON file.

How can this be done with the Google GSON library?

It seems that JsonWriter needs to be used, but I am having trouble finding how to actually write to a new file.

ekeen4
  • 352
  • 1
  • 4
  • 10
  • Your question really has nothing to do with JSON or Gson. All you are really asking is how to write a string to a file. The answer is here: http://stackoverflow.com/questions/15754523/how-to-write-text-file-java – bhspencer Oct 01 '16 at 23:50

1 Answers1

0

JsonWriter's constructor takes another writer as a parameter. You simply need to open a stream on the file you want to write to.

Path fileLocation = Paths.get("/.json");
try (Writer fileWriter = Files.newBufferedWriter(fileLocation, Charset.defaultCharset(), StandardOpenOptions.READ)) {
    try (JsonWriter jsonWriter = new JsonWriter(fileWriter)) {
        // Write your json object using jsonWriter.
        gson.toJson(obj, jsonWriter);
    }
}
Jazzwave06
  • 1,883
  • 1
  • 11
  • 19