2015-06-19 61 views
0

我有以下的域對象創建格姆查詢JSON字符串列表

class ProductQuantity implements Comparable { 

    static constraints = { 
    } 

    Integer quantity 

    static mapping = { 
     version false 
    } 

    static belongsTo = Product 
    static hasMany = [products:Product] 

    int compareTo(obj) { 
     quantity.compareTo(obj.quantity) 
    } 

} 

我想返回一個JSON字符串,看起來像這樣[50,100,200]

隨着格姆,是有沒有去很容易做到這一點,而不必循環對象並創建一個集合?

我開始在這裏

def availableQuantities = ProductQuantity.findAll() 

有什麼建議?

回答

1

假設你從控制器這樣做:

ProductQuantity.list() as JSON 

您可以控制JSON在幾個方面:

1 /註冊BootStrap.groovy中一個JSON編組:

class Bootstrap { 
    def init = { servletContext -> 
     JSON.registerObjectMarshaller(ProductQuantity) { 
      return it.quantity 
     } 
    } 
} 

2 /對於您的簡單情況,您還可以向ProductQuantity類中添加toString方法,該方法返回數量屬性

3 /對於更復雜的用例,可以創建自定義命名配置(如果要從同一個域類生成不同類型的JSON)。 See this post

+0

toString是我所需要的,謝謝 –