Search code examples
grails

Grails View Renders Extra Comma For DTO Object List


I am working on upgrading a Grails 4.0.0 app to 4.0.4. Application is mostly working working. I am having trouble with one GSON view that returns a collection of DTO's (not a domain object).

Versions: Grails 4.0.4, GORM 7.0.6.RELEASE, Win10, openjdk 1.8.0_262

It returns an array of expected objects but, in 4.0.4, with an extra comma before the fields after the opening curly bracket i.e.:

[{,*MY EXPECTED OBJECT 1 DATA*} , {,*MY EXPECTED OBJECT 2 DATA*}] 

which upsets the client. The view looks like:

    import com.myapp.dto.MyDTO
    
    model {
        List<MyDTO> MyDTOList
    }
    
    json g.render(template: "itemView", collection: MyDTOList)

The MyDTOList view causes the problem even with just one field:


    json g.render(MyDTO) {
    afield MyDTO.afield
    }

If I remove the afield from the view (i.e. a blank view) then no extra comma is inserted. Please let me know if I can provide more information. Thanks.


Solution

  • You haven't described the desired structure of the response but here is a reasonable guess...

    See the project at https://github.com/jeffbrown/daftspanieljson.

    https://github.com/jeffbrown/daftspanieljson/blob/dc54db2dc55db36df16338c88c106e67b1c6ecc4/grails-app/controllers/daftspanieljson/MyDTOController.groovy

    package daftspanieljson
    
    import com.myapp.dto.MyDTO
    
    class MyDTOController {
        static responseFormats = ['json', 'xml']
    
        def index() {
            def data = [new MyDTO(afield: 'MY EXPECTED OBJECT 1 DATA'),
                        new MyDTO(afield: 'MY EXPECTED OBJECT 2 DATA')]
    
            respond data
        }
    }
    

    https://github.com/jeffbrown/daftspanieljson/blob/dc54db2dc55db36df16338c88c106e67b1c6ecc4/grails-app/views/myDTO/index.gson

    import com.myapp.dto.MyDTO
    
    model {
        List<MyDTO> myDTOList
    }
    
    json tmpl.itemView(myDTOList)
    

    https://github.com/jeffbrown/daftspanieljson/blob/dc54db2dc55db36df16338c88c106e67b1c6ecc4/grails-app/views/myDTO/_itemView.gson

    import com.myapp.dto.MyDTO
    
    model {
        MyDTO myDTO
    }
    
    json {
        afield myDTO.afield
    }
    

    When I run that app and send a request to that action, I get the following response:

    [
        {
            "afield": "MY EXPECTED OBJECT 1 DATA"
        },
        {
            "afield": "MY EXPECTED OBJECT 2 DATA"
        }
    ]