Saturday, 8 June 2013

conditionally marshalling a grails domain

conditionally marshalling a grails domain

I have a domain Meta with following fields:
class Meta {
  int code
  String errorType
}
I've written a custom marshaller for this which looks like below:
    JSON.registerObjectMarshaller( Meta ) { Meta meta ->
        return [
                code: meta.code,
                errorType: meta.errorType
        ]
    }
Is there a way to conditionally render the JSON for this? So that errorType shows only when there is an actual value in it? For example:
ApiMeta meta = new ApiMeta(code: 400, errorType: "Bad parm")
renders as:
{
  meta:
    {
      code: 400,
      errorType: "Bad parm"
    }
}
However,
ApiMeta meta = new ApiMeta(code: 200)
renders as
{
  meta:
    {
      code: 400,
      errorType: null
    }
}
In this case I want it to leave the errorType property and just render:
{
  meta:
    {
      code: 400,
    }
}

No comments:

Post a Comment