[ 
https://issues.apache.org/jira/browse/GROOVY-10209?page=com.atlassian.jira.plugin.system.issuetabpanels:all-tabpanel
 ]

Daniel Sun reassigned GROOVY-10209:
-----------------------------------

    Fix Version/s: 7.0.0-alpha-1
         Assignee: Daniel Sun

> StackOverflowError in JsonBuilder
> ---------------------------------
>
>                 Key: GROOVY-10209
>                 URL: https://issues.apache.org/jira/browse/GROOVY-10209
>             Project: Groovy
>          Issue Type: Bug
>    Affects Versions: 3.0.8
>            Reporter: A. Lepe
>            Assignee: Daniel Sun
>            Priority: Minor
>              Labels: StackOverflowError, json, jsonBuilder
>             Fix For: 7.0.0-alpha-1
>
>
> The following code throws `_StackOverflowError_`:
> {code:java}
> import groovy.json.JsonBuilder
> def object = [
>     ip   : InetAddress.getByName("192.168.0.1")
> ]
> println new JsonBuilder(object).toPrettyString()
> {code}
> h3. 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.
> h3. For end-users (consumers):
> A work around is to add a `Converter` into `JsonGenerator.Options` to handle 
> your class (e.g. `InetAddress`):
> {code:java}
> JsonBuilder jb = new JsonBuilder(object , new JsonGenerator.Options()
>                 .addConverter(InetAddress, { it.hostAddress })
>                 .build())
> {code}
> h3. 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.



--
This message was sent by Atlassian Jira
(v10.3.26#10030026)

Reply via email to