0

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?

Community
  • 1
  • 1
Ethan K
  • 131
  • 1
  • 9

1 Answers1

2

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.

bdkosher
  • 5,753
  • 2
  • 33
  • 40
  • Unfortunately I am limited by corporate packages - and they are Groovy 2.4.5 which doesn't have JsonGenerator. Is there another option? – Ethan K Mar 05 '20 at 15:06
  • It's not very elegant, but you could convert your object to a `Map`, replacing all `Path` values with corresponding `String` representations. And then you'd serialize the Map instead of the object. – bdkosher Mar 05 '20 at 22:44