Java 8 LocalDate in Grails 3.2 JSON view

允我心安 提交于 2019-12-24 01:22:45

问题


When I try to parse a simple domain model object containing a Java 8 LocalDateTime using a json view, I receive a stack overflow exception, that seems to be related to the fact that the GSON implentation does not know about Java 8 LocalDateTime.

Here is an example (documentation of grails views and JSON):

Domain class "Person"

import java.time.LocalDate
class Person
{
    Sting name
    LocalDate birthDate
}

PersonController

class PersonController
{
    def index() {
        respond Person.findAll() as List<Person>
    }
}

index.gson view

@Field List<Person> personList

json tmpl.person(personList)

_person.gson template file

model 
{
   Person person
}

json g.parse(person)

When I try to open this view, a stack overflow exception is thrown:

Caused by: grails.views.ViewRenderException: Error rendering view: null at grails.views.AbstractWritableScript.writeTo(AbstractWritableScript.groovy:43) at grails.plugin.json.view.api.internal.DefaultGrailsJsonViewHelper$6.writeTo(DefaultGrailsJsonViewHelper.groovy:677)

When I simplify the _person.gson to this:

...
json 
{
   name person.name
}

Thew view works as expected.

My question is

Is there a default way to handle Java 8 LocalDate/Time properties in Grails JSON views? And If not, how can I register a new GSON builder permanently


  • This question is related: How to serialize and deserialize Java 8's java.time types with Gson?
  • I tried to implemented this: https://github.com/gkopff/gson-javatime-serialisers but this won't inject itself as new default de/serializer and needs to be used manually

回答1:


These java 8 date support is not yet implemented in json views. This will work out of the box with views 1.2.0 (when it is released) and the latest version of the grails-java8 plugin at that time.

Edit: To clarify, it is only not supported when using the built in rendering strategy (g.render, hal.render, jsonapi.render, etc). You can still construct the views yourself in any way you want:

json {
    someLocalDate LocalDate.now.format(...)
}

Edit2: Json views 1.2 has been released along with the grails-java8 plugin (also version 1.2). Java 8 date type rendering is now supported out of the box with the 2 plugins together.



来源:https://stackoverflow.com/questions/41056479/java-8-localdate-in-grails-3-2-json-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!