Joseph
Joseph

Reputation: 1463

Grails json cells with enum

In my code I have a domain object with an Enum type in it. That enum type saves and retrieves fine from the database. I am converting a list of domain objects into json cells. All fields except the enum are either a string or a long. When the json gets picked up 'on the other side' it displays [Object object] for the column, instead of the enum name or enum value. Is there something on either the domain or json side that would help with this? Code/example below

Domain Class

class MyDomain {
long id
long otherValue
MyEnum enu  //Nullable per constraints
//Mapping and constraints are not special. 
}

Enum

enum MyEnum {
ENUM1("Value1"),ENUM2("Value2")
//constructor ommitted
String myValue
String toString() { myValue }

Json cell creation

def jsonCells = domainList.collect
    {
        [cell: [
                it.id,
                it.otherValue,
                it.enu?.value
            ],
            id: it.id]
    }

it.enu?.value works. However, is there somehow a better way to do this where I don't have to call the value every time and can rely on the object? I would have assumed that overriding the toString method would have taken care of it, but apparently I was wrong. I know it seems like a minor issue, but its easier to forget ".value", especially as the same enum will be used in many domain objects. Ideas?

Upvotes: 1

Views: 1170

Answers (1)

Rob Hruska
Rob Hruska

Reputation: 120456

Since you're simply putting it in a List when building the object, it will treat it as an Object unless you specifically do something else with it (like you're doing currently).

One alternative would be to use it.enu as String or something similar, but that still probably doesn't achieve what you're trying to achieve.

Another (maybe overengineered?) way would be to create a method on the domain itself that returns the value, and then use that method when building JSON:

class MyDomain {
    MyEnum enu

    def enuVal() {
        enu?.value
    }
}

with

def jsonCells = domainList.collect {
    [cell: [
        it.enuVal()
    ],
    ...]

As for me, I guess I'd just prefer to use it.enu?.val in the JSON. Write a test for your JSON-rendering methods and make sure the value is what you expect it to be, so that you don't forget.

Upvotes: 1

Related Questions