Details
-
Bug
-
Status: Open
-
Minor
-
Resolution: Unresolved
-
3.0.8
-
None
-
None
Description
The following code throws `StackOverflowError`:
import groovy.json.JsonBuilder def object = [ ip : InetAddress.getByName("192.168.0.1") ] println new JsonBuilder(object).toPrettyString()
Explanation:
In `groovy.json.DefaultJsonGenerator.writeObject:170`, if an object class is not found, it will automatically convert it into a map (line 229) and will call the `writeMap` method (line 231).
However, if the object itself contains a field with the same type (in this case InetAddress), it will loop forever:
`writeMap` --> `writeMapEntry` --> `writeObject` --> `writeMap` --> (and so on)
I just discovered that happens with `InetAddress`, but it might happen with other classes as well. Even if its not direct, for example: if `ClassA` contains a `ClassB` field and `ClassB` contains a `ClassA` field.
For end-users (consumers):
A work around is to add a `Converter` into `JsonGenerator.Options` to handle your class (e.g. `InetAddress`):
JsonBuilder jb = new JsonBuilder(object , new JsonGenerator.Options() .addConverter(InetAddress, { it.hostAddress }) .build())
Some options for developers:
- Add support for InetAddress class (so no converter is needed) [partial solution].
- try/catch StackOverflowError and log an explanation on how to solve it.
- Add a max-depth to the JSON tree (maybe not the best idea).
- Evaluate if a class can be easily converted (if it doesn't have any other non-supported classes in it). If it contains other non-supported classes, warn.
- Add an option to auto-convert not-supported classes.