通过支持嵌入式关联反序列化JSON对象

时间:2013-01-16 15:22:32

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

是否有一种简单的方法可以将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();
}

1 个答案:

答案 0 :(得分:0)

您是否尝试过使用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

尝试此操作。