2016-04-09 8 views
2

オブジェクトをJSONに変換しようとしています。オブジェクトには、オブジェクトを変換するはずの特性があります。しかし、私は奇妙なjson結果を取得します。json coversionの特性を持つgroovyオブジェクト

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                                       
} 

だから、私はこのようにそれを行うことができないようですか?

答えて

3

まあ、何でも。 withTraitsを使用すると、元のオブジェクトのプロキシの作成につながります。私は現在の実装でこのように解決しました。

trait JsonPackageTrait { 
    def toJson() { 
     JsonOutput.prettyPrint(
      JsonOutput.toJson(this.$delegate) 
     ) 
    } 
} 
関連する問題