Amarnath R
Amarnath R

Reputation: 1003

Grails - Return selected json elements from request parameter

In my project, I am trying to return selected elements as JSON from requested parameter.

Domain Class:

class Component{
    String name
    String level
    .
    .
    .
}

I have http request like

http://localhost:8080/myapp/component/showJson?name=name

so I should return only

{
   name:xyz
}

If my request is like

http://localhost:8080/myapp/component/showJson?name=name&level=level

Then I should return

{
     name:xyz
     level:1
}

Any suggestions is appreciated.

Updated JSON (Multilevel)

[
   {"name":"one","level":0," 
         componentTypes":[
                {"name":"one one","level":1,
                    "componentTypes":[
                      {"name":"one one one","level":2,"componentTypes":[]}
                    ]
                 },
                 {"name":"one two","level":1,"componentTypes":[]}
         ]
   }, 
   {"name":"two","level":0,"componentTypes"[]},
   {"name":"three","level":0,"componentTypes":[]}
]

class ComponentType {
    String name
    Integer level
    static hasMany = [componentTypes:ComponentType]
    ComponentType parent
    static constraints = {
        parent nullable:true
    }
    static mapWith = "mongo"
}

Controller action

componentTypeList = ComponentType.createCriteria().list(){
            eq("level", 0)
        }

Upvotes: 1

Views: 84

Answers (1)

JChap
JChap

Reputation: 1441

You can intersect the params map with object properties map and return the result. I haven't tried this, but i can't think of a reason why it will not work.

def properties = component.properties;
def result = properties.subMap(params.keySet())
render result as JSON

Update:

class ComponentType {

    .
    .
    .



    def toJSON(def params) {
        def properties = this.properties
        def result = properties.subMap(params.keySet())
        if(this.componentTypes) {
            result.componentTypes = componentTypes*.toJSON(params)
        }
        result
    }
}


def componentTypeList = ComponentType.createCriteria().list(){ eq("level", 0) } 
render componentTypeList*.toJSON(params) as JSON

Upvotes: 2

Related Questions