5

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

1 回答 1

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

试试这个会奏效。

于 2013-01-29T08:51:03.647 回答