具有特征到json转换的groovy对象

时间:2016-04-09 17:21:47

标签: 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                                                                                                                                                          
}

所以我觉得我不能这样做吗?

1 个答案:

答案 0 :(得分:3)

嗯,无论如何。由于使用withTraits导致创建原始对象的代理,我为我当前的实现解决了这个问题

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