dbrin
dbrin

Reputation: 15673

Grails JSON Converters and transient properties

Using Grail 1.3.7 I found that the JSON converter ignores transient properties of Domain objects. Question: Is there an elegant way to work around this obstacle.

Bonus question: what's the reasoning behind excluding calculated fields(transient props) from being sent to the response????

Upvotes: 6

Views: 4653

Answers (5)

jmendiola
jmendiola

Reputation: 413

You could use the "marshallers" plug-in and define you transient property as virtual like this:

    static marshalling = {
      virtual {
        yourPropery { value, json -> json.value(value.yourPropery) }
      }
    }

Upvotes: 0

Vlad
Vlad

Reputation: 91

what works for me is this one line

def jsonobj=domobj.properties as JSON

Upvotes: 9

Dónal
Dónal

Reputation: 187499

If you need fine-grained control over the fields that are included/excluded in the JSON, I fine using the JSONBuilder a better option than the converter. Here's an example of how to do this.

Upvotes: 0

hitty5
hitty5

Reputation: 1673

one way would be to manually create your json response, e.g.

["prop1" : obj.prop1, "prop2" : obj.prop2, ...] as JSON

Upvotes: 5

Igor Artamonov
Igor Artamonov

Reputation: 35961

Transient is made exactly for that: Variables may be marked transient to indicate that they are not part of the persistent state of an object

And JSON is an serialized (=persistent) state of object

So, if you need it to be serialized - you have to create an new class, just for json serialization, that will have all fields you need to serialize.

Upvotes: 5

Related Questions