Grails - grails.converters.JSON - 删除类名

Bud*_*Joe 12 grails serialization json jsonserializer

有没有办法删除JSON转换器中的类字段?

例:

import testproject.*
import grails.converters.*  
emp = new Employee()  
emp.lastName = "Bar"  
emp as JSON  
Run Code Online (Sandbox Code Playgroud)

作为一个字符串是

{"class":"testproject.Employee","id":null,"lastName":"Bar"}
Run Code Online (Sandbox Code Playgroud)

我更喜欢

{"id":null,"lastName":"Bar"}
Run Code Online (Sandbox Code Playgroud)

有没有办法在最后添加一行代码来删除类字段?

wwa*_*ock 12

这是一种方法.我在域类中添加了下一个代码:

static {
    grails.converters.JSON.registerObjectMarshaller(Employee) {
    return it.properties.findAll {k,v -> k != 'class'}
    }
}
Run Code Online (Sandbox Code Playgroud)

但正如我发现你在使用Groovy @ToString类注释时还必须添加'class'来排除参数,例如:

@ToString(includeNames = true, includeFields = true, excludes = "metaClass,class")
Run Code Online (Sandbox Code Playgroud)


klo*_*ogd 7

我喜欢这样做的首选方式:

def getAllBooks() {
    def result = Book.getAllBooks().collect {
        [
            title: it.title,
            author: it.author.firstname + " " + it.author.lastname,
            pages: it.pageCount,
        ]
    }
    render(contentType: 'text/json', text: result as JSON)
}
Run Code Online (Sandbox Code Playgroud)

这将返回Book.getAllBoks()中的所有对象,但collect方法将ALL更改为您指定的格式.