Ethan K
Ethan K

Reputation: 140

Serialize java.nio.file.Path with JsonBuilder in Groovy

I am trying to serialize an object which holds an instance of java.nio.file.Path and since path is an interface I am receiving a StackOverflow Exception

I have checked this answer: https://stackoverflow.com/a/36966590/11325201 and wanted to implement a type adapter for my use case in groovy but I didn't find JsonBuilder's equivalent of GsonBuilder's registerTypeAdapter or registerTypeHierarchyAdapter

How can I achieve a similar solution in Groovy?

Upvotes: 0

Views: 417

Answers (1)

bdkosher
bdkosher

Reputation: 5893

You can pass a JsonGenerator object to your builder when you construct it. This object allows you to specify various options, including type converters, which you register with the Class and a closure. In this example, the converter just calls the toString on the Path.

def generator = new JsonGenerator.Options()
                                 .addConverter(Path) { Path p -> p.toString() }
                                 .build()                 

def json = new JsonBuilder(myObjContainingPathProperties, generator).toPrettyString()

The online GroovyDocs for JsonGenerator do not show anything (likely a GroovyDoc generator bug in version 3.0), but the GroovyDocs for 2.5 work.

Upvotes: 2

Related Questions