2014-12-04 42 views
0

我知道在grails中我可以定義不同的JSON marshallers併爲它們設置不同的用途名稱,這非常好。然而,我在Bootstrap部分結束了很多代碼,並且結束了兩個我需要調整域類更改時的地方。Grails類域中的JSON marshallers

Ithink thi不夠好,我不知道是否可以在域類本身中定義JSON marshallers。

你認爲這是一個很好的做法嗎? ...你能提供一些建議來達到這個目標嗎?

感謝,

+1

這完全取決於你如何管理你的代碼。我通常會爲Marshallers創建一個MarshallerBootstrap.groovy。這裏還有另一個想法:http://compiledammit.com/2012/08/16/custom-json-marshalling-in-grails-done-right/ – 2014-12-04 11:17:15

回答

1

BootStrap.groovy中編寫代碼:

JSON.registerObjectMarshaller(YourClass) { YourClass yourClass-> 
     Map result = [:] 
     result['yourClass.property'] = yourClass.property 
     def domain = new DefaultGrailsDomainClass(YourClass) 
     domain.persistentProperties.each { GrailsDomainClassProperty property, String propertyName = property.name -> 
       result[propertyName] = yourClass[(propertyName)]  
     }   
     return result 
    } 

代碼下面添加一個屬性,你可以將其命名如何ü希望

result['yourClass.property'] = yourClass.property 

該代碼添加由它的名字的所有屬性映射:

domain.persistentProperties.each { GrailsDomainClassProperty property, String propertyName = property.name -> 
       result[propertyName] = yourClass[(propertyName)]  
     }  
+0

什麼是「事件[propertyName」中的事件? – Kachwahed 2016-03-30 15:17:03

+0

@Kachwahed是的,有錯誤。應該是yourClass [(propertyName)] – Koloritnij 2016-03-31 20:41:54

2

我寫了用於此目的的專門plugin。它可以讓你在領域類使用註釋,像這樣:

import grails.plugins.jsonapis.JsonApi 
class User { 

    static hasMany = [ 
     pets: Pet 
    ] 

    @JsonApi 
    String screenName 

    @JsonApi('userSettings') 
    String email 

    @JsonApi(['userSettings', 'detailedInformation', 'social']) 
    String twitterUsername 

    @JsonApi(['detailedInformation', 'userSettings']) 
    Set pets 

    String neverGetsSerialized 

    @JsonApi('detailedInformation') 
    Integer getNumberOfTicklyAnimals() { 
     pets.count { it.likesTickling } 
    } 
} 

在你的控制,你會再調用​​激活特定的編組。

+0

mmm ...對我來說很好看! ...也許這個名字可以改進,但看起來很有趣 – Rafael 2014-12-04 11:59:21

+0

»計算機科學中只有兩件難事:緩存失效和命名事物。 «;) – 2014-12-04 12:02:16