grails-views icon indicating copy to clipboard operation
grails-views copied to clipboard

GSON-Views can't handle immutability?

Open davidkron opened this issue 2 years ago • 0 comments

We integrated grails-views into an older existing application to provide a good JSON developer experience for newly created and modern single-page applications. We already had some JSON-Endpoints that render a simply model using the Grails JSON marshaller like this:

respond(result, formats: ['json'])

A lot of those broke in our application and the reason seems to be that grails-views can't handle immutable models, which seems like a major flaw in this library. The code where this is explicitly implemented is right here: https://github.com/grails/grails-views/blob/2.3.x/json/src/main/groovy/grails/plugin/json/view/api/internal/DefaultGrailsJsonViewHelper.groovy#L387

For grails-views we also implemented the default template /grails-app/views/object/_object.gson exactly as described in the documentation, as we do want to fallback to a default behavior, when no explicit gson-view is available. When this view is not found it seems to work, as the fallback is to use the Grails JSON marshaller (like when not using grails-views). But this is a workaround not a real solution.

This following code doesn't produce the expected JSON result:

class TestController {
    def index() {
        def result = new MyResult("Hello World!")
        respond(result, formats: ['json'])
    }
}

@TupleConstructor
class MyResult {
    final String text
}

Response: {}

If I remove the final from the model it works:

@TupleConstructor
class MyResult {
    String text
}

Response:

{
    "text": "Hello World!"
}

davidkron avatar Nov 23 '22 10:11 davidkron