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

后端 未结 7 855
梦如初夏
梦如初夏 2020-12-16 00:14

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

Example:

import testproject.*
import grails.converters.*  
emp = new Employee()  
emp         


        
7条回答
  •  旧时难觅i
    2020-12-16 00:53

    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

提交回复
热议问题