3

I'm making a unit test that needs to return JSON. To build that I'm using toPrettyString() method from JSONBuilder.

This is the class to 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 spec to run is this:

@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 repeating until the end.

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

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

    String aux = lugar.toJson();

    println aux.dump()
}

The results were:

{
    "sigla": "BUE",
    "constraints": {
        "nombre": {
            "blank": false,
            "nullable": false
        }
    },
    "nombre": "BUENOS AIRES"
}
Burt Beckwith
  • 75,342
  • 5
  • 143
  • 156
paulofer85
  • 555
  • 11
  • 15

1 Answers1

0

I wouldn't make the object itself responsible for formatting it's contents. First, you might look at the @ToString annotation, which allows you to specify what 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 let the default json converter handle it. Something like println new JsonBuilder( object ).toPrettyString()

see: Groovy - Convert object to JSON string

Community
  • 1
  • 1
Jabrwoky
  • 61
  • 6