gpt4 book ai didi

json - Grails - 如何让域类将 JSON 转换为域属性

转载 作者:行者123 更新时间:2023-12-02 14:45:39 25 4
gpt4 key购买 nike

我想教我的域类自动将 JSON.parse(someJSON) 的结果转换为也是自定义域类的成员。

给定这些域类:

class Person {
Long id
String name

static hasMany = [aliases: PersonAlias]
}

class PersonAlias {
Person person
Long id
String name
}

这个 JSON 代表一个带有一些 PersonAliases 的人:
{
"id":20044397,
"name":"John Smith",
"aliases":[{"id":13376,"name":"Johnny Smith"},{"id":13377,"name":"J. Smith"}]
}

我想保持 Controller 简单,例如:
class PersonController {
def saveViaAjax = {
def props = JSON.parse(params.JSON)
Person p = Person.get(props.id)
p.properties = props
p.save(flush: true)
}
}

但遗憾的是我收到了这个错误:

Failed to convert property value of type 'org.codehaus.groovy.grails.web.json.JSONArray' to required type 'java.util.Set' for property 'aliases'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [org.codehaus.groovy.grails.web.json.JSONObject] to required type [heavymeta.PersonAlias] for property 'aliases[0]': no matching editors or conversion strategy found



所以,我想教我的领域类如何将 JSON 数据自动转换为 PersonAlias 实例。我想避免在将 Controller 中的数据传递给域对象之前对其进行格式化。我如何实现这些目标?

最佳答案

您可以使用 bindUsing注释并提供您的自定义绑定(bind)代码以将 json 转换为要绑定(bind)的属性。

class Person {
Long id
String name

@BindUsing({obj, source ->
List retVal = []
def aliases = source['aliases']
if(aliases) {
aliases.each {
retVal << new PersonAlias(name:it.name)
}
}
return retVal
})
List<PersonAlias> aliases

static hasMany = [aliases: PersonAlias]
}

关于json - Grails - 如何让域类将 JSON 转换为域属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11838501/

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