0

I have the following domain class

class Settings {
    static constraints = {
        pageID(nullable: false, unique: true)
        lp()
    }

    String pageID
    Map lp
}

I'm querying the DB like SO:

...
def query = Settings.where {pageID == id}
def result = query.find()

Here is a screen shot of the evaluated result: enter image description here

Now I'm looking for a way to format the result as a JSON like so:

{"lp":{"account":"12345678","appKey":"64dsfg64dg64fg65dfg6","domain":"my.domain.com"},"pageID":"123456"}

What is the right way to extract the fields out? It would be best if I can avoid getting each field manually. Thanks :)

Community
  • 1
  • 1
Shlomi Schwartz
  • 8,693
  • 29
  • 109
  • 186

2 Answers2

1

Since I did not find a native function, I used @Jinzhao Wu approach and wrote this helper function:

def getDBRecord(Object dc) {
    def jo = new JSONObject()
    def domainClass = new DefaultGrailsDomainClass(dc.class)
    def props = domainClass.getPersistantProperties()
    for (int i = 0; i < props.length; i++) {
        jo.put(props[i].name, dc[props[i].name]);
    }
    return jo;
}

Hope that help others

Shlomi Schwartz
  • 8,693
  • 29
  • 109
  • 186
0

Just use gorm dynamic finder:

def result = Settings.findByPageId(id)
render result as JSON
coderLMN
  • 3,076
  • 1
  • 21
  • 26
  • Hi, Thanks for the reply, however I still get fields that are not a part of my domain class (like :errors, metaClass etc') so if I render it as JSON my client gets extra redundant fields – Shlomi Schwartz Jan 06 '13 at 08:27
  • Use remove method like result.remove('errors') to get rid of useless fields. Or render result.persistentProperties – coderLMN Jan 06 '13 at 08:45
  • That's what I do right now, I feel it is the wrong way. As I see it there must be a more elegant way to get just the fields you defined in the domain class. – Shlomi Schwartz Jan 06 '13 at 10:00
  • The way you put in your answer is not what I recommended. – coderLMN Jan 06 '13 at 11:07