Enumerating Grails in JSON

I would like to change the way redistribution of enums in JSON. I am currently using default grails.converters.JSON (as JSON) and, for example, in the controller that I am using:

FilmKind.values ​​() as JSON

The result of this:

"kind":[{"enumType":"FilmKind","name":"DRAMA"},{"enumType":"FilmKind","name":"ACTION"}]

I would like to remove "enumType" and just return:

"kind":["DRAMA","ACTION"]

I am looking for a solution that will still allow me to use

like json

because I don’t want to sort each listing individually.

+5
source share
4 answers

because I don’t want to sort each listing individually.

, JSON, . , - , , , . FilmKind , .

, . FilmKindMarsaller:

class FilmKindMarshaller {
  void register() {
    JSON.registerObjectMarshaller(FilmKind) { FilmKind filmKind ->
      [
          name: filmKind.toString()

      ]
    }
  }
}

Bootstrap:

[ new FilmKindMarshaller() ].each { it.register() }

, , .

, FilmKind JSON'ified, , JSON, , enumType.

+10

, - , String:

class EnumTypeHidingJSONMarshaller {
    void register() {
        JSON.registerObjectMarshaller(Enum) { Enum someEnum ->
            someEnum.toString()
        }
    }
}
+13

, as JSON. Bootstrap.groovy - :

JSON.registerObjectMarshaller(FilmKind) {
    def result = [:]
    def props = ['name']
    props.each { prop ->
        result[prop] = it."$prop"
    }
    result
}
+2
source

What about:

def display = [kind:[]]
FilmKind.values().each { val ->
  display.kind.add(val.value)
}

render display as JSON
+1
source

All Articles