具有trait到json转换的groovy对象



我正在尝试将对象转换为JSON。对象具有一个特性,该特性应该转换对象。但我得到了奇怪的json结果。

import groovy.json.*
trait JsonPackageTrait {
    def toJson() {
        JsonOutput.prettyPrint(
            JsonOutput.toJson(this)
        )
    }
}
class Item {
    def id, from, to, weight
}
def item = new Item()
item.with {
    id = 1234512354
    from = 'London'
    to = 'Liverpool'
    weight = 15d.lbs()
}
item = item.withTraits JsonPackageTrait
println item.toJson()

JSON结果

{                                                                                                                                                                             
    "from": "London",                                                                                                                                                         
    "id": 1234512354,                                                                                                                                                         
    "to": "Liverpool",                                                                                                                                                        
    "proxyTarget": {                                                                                                                                                          
        "from": "London",                                                                                                                                                     
        "id": 1234512354,                                                                                                                                                     
        "to": "Liverpool",                                                                                                                                                    
        "weight": 33.069                                                                                                                                                      
    },                                                                                                                                                                        
    "weight": 33.069                                                                                                                                                          
}

看来我不能这样做?

好吧,不管怎样。由于使用withTraits导致创建原始对象的代理,我为当前实现解决了这个问题

trait JsonPackageTrait {
    def toJson() {
        JsonOutput.prettyPrint(
            JsonOutput.toJson(this.$delegate)
        )
    }
}

最新更新