Grails - JSONBuilder - Spec toPrettyString () returns stackoverflow

I am creating a unit test that should return JSON. To create this, I am using a method toPrettyString()

from JSONBuilder.

This is the class for the spec:

class Lugar {
   String sigla
   String nombre
   Coordenada coordenada

   String toString(){
      "${sigla}"
   }

   String toJson()
   {
      new JsonBuilder( this ).toPrettyString()
   }

   static constraints = {
      nombre blank: false , nullable: false
   }
}

      

The specification for launch is as follows:

@TestFor(Lugar)
class LugarSpec extends Specification {

    void "toJson not empty"() {

        when:
        Lugar lugar = new Lugar(sigla: "BUE", nombre:"BUENOS AIRES")
        String aux = lugar.toJson();

        then:
        ! aux.dump().empty
    }
}

      

But the result is:

 <error type="java.lang.StackOverflowError">java.lang.StackOverflowError
    at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1270)
    at groovy.lang.MetaBeanProperty.getProperty(MetaBeanProperty.java:60)
    at groovy.lang.PropertyValue.getValue(PropertyValue.java:40)
    at groovy.json.JsonOutput.writeObject(JsonOutput.java:287)
    at groovy.json.JsonOutput.writeMap(JsonOutput.java:421)
    at groovy.json.JsonOutput.writeObject(JsonOutput.java:291)
    at groovy.json.JsonOutput.writeArray(JsonOutput.java:326)
    at groovy.json.JsonOutput.writeObject(JsonOutput.java:283)
    at groovy.json.JsonOutput.writeMap(JsonOutput.java:421)
    at groovy.json.JsonOutput.writeObject(JsonOutput.java:291)
    at groovy.json.JsonOutput.writeArray(JsonOutput.java:326)
    at groovy.json.JsonOutput.writeObject(JsonOutput.java:283)
    at groovy.json.JsonOutput.writeMap(JsonOutput.java:421)
    at groovy.json.JsonOutput.writeObject(JsonOutput.java:291)

      

And it continues to repeat itself to the end.

I tried to test toJson on main and the results were accurate:

static void main(String[] args) {
    Lugar lugar = new Lugar(sigla: "BUE", nombre:"BUENOS AIRES")

    String aux = lugar.toJson();

    println aux.dump()
}

      

Results:

{
    "sigla": "BUE",
    "constraints": {
        "nombre": {
            "blank": false,
            "nullable": false
        }
    },
    "nombre": "BUENOS AIRES"
}

      

+3


source to share


1 answer


I would not be the object itself to be responsible for formatting the content. First, you can look at the @ToString annotation, which allows you to specify which fields to include in the result.

http://docs.groovy-lang.org/latest/html/gapi/groovy/transform/ToString.html



Second, I would remove the toJson method and just allow the default json handler. Something like println new JsonBuilder (object) .toPrettyString ()

see: Groovy - Convert Object to JSON String

0


source







All Articles