gpt4 book ai didi

json - chalice /JSON : recursive data structre for JSON#registerObjectMarshaller

转载 作者:行者123 更新时间:2023-12-02 14:42:47 26 4
gpt4 key购买 nike

我有以下自引用(递归)类:

class Node {

String label
// other attributes go here
static belongsTo = [parent: Node]
static hasMany = [children: Node]

static constraints = {
label blank: false
parent nullable: true
children nullable: true
}
}

我在 BootStrap.groovy 中使用了编码器,因为我只想将一些选择属性发送到客户端,在这个阶段只有标签:
JSON.registerObjectMarshaller(Node) { Node node ->
return [label: node.label, items: node.children]
}

创建节点的层次结构,例如:
def parent1 = new Node(label: "Node 1").save(flush: true)
parent1.addToChildren(new Node(label: "Node 1.1"))

def parent2 = new Node(label: "Node 2").save(flush: true)
def child21 = new Node(label: "Node 2.1")
child21.addToChildren(new Node(label: "Node 2.1.1"))
parent2.addToChildren(child21)

并像这样列出它们:
def index(Integer max) {
params.max = Math.min(max ?: 10, 100)

respond Node.list(params), model: [nodeInstanceCount: Node.count()]
}

我想要类似的东西:
Node 1
|
-- Node 1.1
Node 2
|
-- Node 2.1
|
-- Node 2.1.1

结果看起来很有希望,但有几个节点太多:
Node 1
|
-- Node 1.1
Node 2
|
-- Node 2.1
|
-- Node 2.1.1
Node 1.1
Node 2.1
|
-- Node 2.1.1
Node 2.1.1

输出是不希望的,但很有意义:对于每个节点,都会调用此方法,因此会产生额外的层次结构/单个节点。

我尝试解决此问题的一种方法是在 Node 类中添加一个“已处理”属性。这具有预期的效果(每个节点只处理一次,从而产生所需的层次结构),但引入了以后必须管理该状态变量的问题。因此,我想避免这种黑客攻击。
另一种方法是让客户端处理接收到的数据

有没有简单的方法来克服这个问题?

最佳答案

发布上述问题后,我找到了罪魁祸首。我希望有一天这会对某人有所帮助,以防他们遇到类似的问题。
Node#list当我们想要的只是顶级节点时,显然返回所有节点:

respond Node.list(params), model: [nodeInstanceCount: Node.count()]

要直接跳到答案,以下解决了该问题:
  • 添加 isRoot节点属性

  • 然后改 index()到以下:
    respond Node.findAllByIsRoot(true), model: [nodeInstanceCount: Node.count()]

    提供更多细节:
  • 用于将此数据转换为所需 JSON 格式的编码器(由 #respond 方法决定,例如通过查看 ACCEPTCONTENT-TYPE header ,或者在本例中查看 format 中的字段请求 URI(在 UrlMappings#mappings 中定义)将是类型

    org.codehaus.groovy.grails.web.converters.marshaller.json.CollectionMarshaller

    因此对于列表中的每个对象,编码器被称为
  • 集合编码器然后委托(delegate)给伴随的转换器,在我们的例子中是类型

    grails.converters.JSON
  • 在其JSON#value方法,它最终会调用 BootStrap.groovy 中定义的闭包我们注册编码时的类(class)
  • 关于json - chalice /JSON : recursive data structre for JSON#registerObjectMarshaller,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25743149/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com