【问题标题】:Deserialize a JSON object with support for embedded associations反序列化支持嵌入式关联的 JSON 对象
【发布时间】:2012-12-30 23:17:05
【问题描述】:

是否有一种简单的方法可以将 JSON 字符串反序列化为支持嵌入式关联的域类; belongsTo 和 hasMany

{
  name: "Customer",
  contact: {
    name: "Contact"
  }
} 

class Customer {
  name 
  Contact contact
}

class Contact {
  String name
  static belongsTo = [customer:Customer]
}

在我的控制器中,我想执行以下操作

def save() {
   def customer = new Customer(request.JSON)
   customer.save();
}

现在我不得不这样做

def save() {
   def contact = new Contact(request.JSON.contact);
   def customer = new Customer(request.JSON);
   customer.contact = contact;
   customer.save();
}

【问题讨论】:

  • grails.converters.json.default.deep 设置为 true?
  • 所以为了给你一个想法,你必须将其转换为:{ name: "Customer", contact.name: "Contact" }
  • grails.converters.json.default.deep 根本没有设置,当我在 config.groovy 中将其设置为 true 时没有任何区别
  • @JamesKleeh Geee 如果这是真的,那真是违反直觉。它应该在解析 JSON 时在内部处理。
  • 好吧,数据绑定是用于从 html 表单设置数据,而不是从 JSON 设置数据,因此它不是为获取对象而设计的,因为在表单上这样做没有任何意义。

标签: grails grails-2.0 grails-domain-class grails-controller


【解决方案1】:

您是否尝试过使用 JsonSlurper?

示例用法:

def slurper = new JsonSlurper()
def result = slurper.parseText('{"person":{"name":"Guillaume","age":33,"pets":["dog","cat"]}}')

assert result.person.name == "Guillaume"
assert result.person.age == 33
assert result.person.pets.size() == 2
assert result.person.pets[0] == "dog"
assert result.person.pets[1] == "cat"

参考:http://groovy.codehaus.org/gapi/groovy/json/JsonSlurper.html

你可以试试这个

    Test test
    def result = new JsonSlurper().parseTest('yourString')
    test = result

试试这个就行了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-23
    • 2014-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-08
    • 2011-08-14
    • 2019-03-08
    相关资源
    最近更新 更多