lapots
lapots

Reputation: 13395

groovy object with trait to json conversion

I am trying to convert object to JSON. Object has a trait which supposed to convert object. But I get weird json result.

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 result

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

So it seems I cannot do it like this?

Upvotes: 3

Views: 122

Answers (1)

lapots
lapots

Reputation: 13395

Well, whatever. As using withTraits leads to creating proxy of the original object I resolved like this for my current implementation

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

Upvotes: 3

Related Questions