json - Grails-从请求参数返回选定的json元素

标签 json grails

在我的项目中,我试图从请求的参数中将选定的元素作为JSON返回。

域类:

class Component{
    String name
    String level
    .
    .
    .
}

我有喜欢的http请求
http://localhost:8080/myapp/component/showJson?name=name

所以我应该只回来
{
   name:xyz
}

如果我的要求是
http://localhost:8080/myapp/component/showJson?name=name&level=level

那我应该回来
{
     name:xyz
     level:1
}

任何建议表示赞赏。

更新了JSON(多级)
[
   {"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)
        }

最佳答案

您可以将params贴图与对象属性贴图相交并返回结果。我没有尝试过,但是我想不出它为什么不起作用的原因。

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

更新:
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

关于json - Grails-从请求参数返回选定的json元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36196052/

相关文章:

java - 如何在Java中解析JSON

c# - 根据节点名称拆分大型 JSON 的通用代码

php - 如何将特定变量从 PHP 返回到 Android

json - 我可以在 Azure 中解析 IoT 数据,以便随后将其保存到 SQL DB

grails - CamelExchangeException:无法将响应写入...由UnsupportedException引起

c - C 调试功能中的 Visual Studio Code Hello World 不起作用 Programm NullReferenceException :

grails - Grails应用程序未从云前端加载js和CSS

session - 集成测试期间未设置Grails session 对象属性

grails - Grails密码约束功能

grails - 如何从 Servlet3SecurityContextHolderAwareRequestWrapper 中获取 MultipartRequest