Grails - grails.converters.JSON - removing the class name

£可爱£侵袭症+ 提交于 2019-11-27 16:11:50

问题


Is there a way to remove the class field in a JSON converter?

Example:

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

as a string is

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

I'd prefer

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

Is there a way to add one more line of code at the end to remove the class field?


回答1:


Here is yet one way to do it. I've added a next code to the domain class:

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

But as I found if you have used Groovy @ToString class annotation when you also must add 'class' to excludes parameter, e.g.:

@ToString(includeNames = true, includeFields = true, excludes = "metaClass,class")



回答2:


My preferred way of doing this:

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)
}

This will return all the objects from Book.getAllBoks() but the collect method will change ALL into the format you specify.




回答3:


One alternative is to not use the builder:

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

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

This is a bit less orthogonal since you'd need to change your rendering if Employee changes; on the other hand, you have more control over what gets rendered.




回答4:


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())



回答5:


@wwarlock's answer is partly right, I have to put the registerObjectMarshaller on Bootstrap, it can work.




回答6:


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) }
        }
    }
}

This works for me. You can easily pass in any property to exclude. Or turn it around:

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) }
        }
    }
}

Beware: This is only for simple objects. If you see "Misplaced key: expected mode of KEY but was OBJECT" this solution is not for you. :)

HP




回答7:


You can customize the fields to be excluded (including the class name) using the setExcludes method provided in the grails.converters.JSON

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

and then, you can use it just like according to your requirements,

println converter.toString()
converter.render(new java.io.FileWriter("/path/to/my/file.xml"))
converter.render(response)


来源:https://stackoverflow.com/questions/6495633/grails-grails-converters-json-removing-the-class-name

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