Search code examples
grailsgrails-orm

Flatten a nested Grails Domain object


Concerning to this question, having this set of Grails domain classes:

class Hero {
    String name
    Float level

    static hasOne = [familiar: Familiar]
}

class Familiar {
    String name
    Integer raceId

    static belongsTo = [hero: Hero]
}

How can I change the result of querying Hero from:

[
    name: "Emphraim",
    level: 99.0,
    familiar: {
        name: "Mhyrr",
        raceId: 1
    }
]

to a flat one:

[
    {
        "name": "Ephraim"
        "level": 99.0,
        "familiar_name": "Mhyrr"
        "familiar_raceId": 1
    }
]

without mapping it one by one to a new HashMap? I query Hero class using this code:

def hero = Hero.find {
    eq("name", "Ephraim")
}

Solution

  • As Joshua mentioned, you would need a custom marshaller. There are different ways to do it but I would recommend this plugin