Reputation: 15909
i am wondering what i am missing in adding dynamic properties to a java class and trying to render that class using the JSON converter. I have a pure java pojo and i am adding a dynamic property to it using:
// adding property
ResetRequest.metaClass.targetIp = "192.168.0.1"
// creating object
ResetRequest obj = new ResetRequest()
// printing the properties
println obj.properties
When printing the properties the object has a additional property called 'targetIp' so all seems ok, but when i try to render the object as JSON the added property is not in the JSON string.
Any suggestion what i am missing.
Upvotes: 0
Views: 752
Reputation: 995
You should register custom property in Bootstrap like
def init = { servletContext ->
ResetRequest.metaClass.targetIp = {req ->
return "192.168.0.1";
}
}
Upvotes: 1
Reputation: 4811
I think the JSON conversion in grails does not pick up dynamically added properties.
Maybe you should register your own object marshaller for the class in question?
In Bootstrap:
def init = {servletContext ->
JSON.registerObjectMarshaller(ResetRequest) {req->
[
targetIp:req.targetIp
//etc
]
}
UPDATE This link shows how you can inherit from the default Marshaller and add your own logic to marshall specific fields:
http://grails4you.com/2012/04/restful-api-for-grails-domains/
Upvotes: 3