12

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

例子:

import testproject.*
import grails.converters.*  
emp = new Employee()  
emp.lastName = "Bar"  
emp as JSON  

作为一个字符串

{"class":"testproject.Employee","id":null,"lastName":"Bar"}

我更喜欢

{"id":null,"lastName":"Bar"}

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

4

7 回答 7

12

这里还有一种方法可以做到这一点。我在域类中添加了下一个代码:

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

但是正如我发现的那样,当您还必须将“类”添加到排除参数时,如果您使用了 Groovy @ToString 类注释,例如:

@ToString(includeNames = true, includeFields = true, excludes = "metaClass,class")
于 2012-09-24T05:12:39.530 回答
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)
}

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

于 2012-10-12T08:34:18.553 回答
3

一种替代方法是不使用构建器:

def myAction = {
    def emp = new Employee()
    emp.lastName = 'Bar'

    render(contentType: 'text/json') {
        id = emp.id
        lastName = emp.lastName
    }
}

这有点不正交,因为如果 Employee 更改,您需要更改渲染;另一方面,您可以更好地控制渲染的内容。

于 2011-06-27T16:09:36.590 回答
1

@wwarlock 的回答部分正确,我必须将 registerObjectMarshaller 放在 Bootstrap 上,它可以工作。

于 2013-09-06T01:38:48.037 回答
1
def a = Employee.list()

String[] excludedProperties=['class', 'metaClass']
render(contentType: "text/json") {
    employees = array {
        a.each {
            employee it.properties.findAll { k,v -> !(k in excludedProperties) }
        }
    }
}

这对我有用。您可以轻松传入任何要排除的属性。或者反过来:

def a = Employee.list()

String[] includedProperties=['id', 'lastName']
render(contentType: "text/json") {
    employees = array {
        a.each {
            employee it.properties.findAll { k,v -> (k in includedProperties) }
        }
    }
}

注意:这仅适用于简单对象。如果您看到“错位的密钥:KEY 的预期模式但为 OBJECT”,则此解决方案不适合您。:)

生命值

于 2014-07-30T13:01:06.570 回答
1
import testproject.*
import grails.converters.*  
import grails.web.JSONBuilder

def emp = new Employee()  
emp.lastName = "Bar"  

def excludedProperties = ['class', 'metaClass']

def builder = new JSONBuilder.build {
  emp.properties.each {propName, propValue ->

  if (!(propName in excludedProperties)) {
    setProperty(propName, propValue)
  }
}

render(contentType: 'text/json', text: builder.toString())
于 2011-06-28T08:01:40.563 回答
1

您可以使用 grails.converters.JSON 中提供的 setExcludes 方法自定义要排除的字段(包括类名)

def converter = emp  as JSON
converter.setExcludes(Employee.class, ["class",""])

然后,您可以根据自己的要求使用它,

println converter.toString()
converter.render(new java.io.FileWriter("/path/to/my/file.xml"))
converter.render(response)
于 2016-09-30T09:12:30.283 回答