Include transient domain class properties as dossier json or xml response in grails

I have read many ways to try and achieve this, but I would have thought it would be pretty easy?

Given the domain class:

class DomainClassTest{
    String foo
    String bar

    //add accessor
    String getMessage() {
        "Hello"
    }
}

      

I would like to include the "message" transient property in both the xml and json responses.

What's the easiest way to do this?

I've read the documentation for the renderers; http://grails.org/doc/latest/guide/single.html#renderers

I've tried the following:

DomainClassTestController.groovy:

class DomainClassTestController extends RestfulController<DomainClassTestController>{
    static responseFormats = ['xml','json']

    DomainClassTestController() {
        super(DomainClassTest)
    }
}

      

/CONF/spring/resources.groovy

beans = {
    xmlDomainClassTestRenderer(XmlRenderer, DomainClassTest) {
        includes = ['message']
    }
    jsonDomainClassTestRenderer(JsonRenderer, DomainClassTest) {
        includes = ['message']
    }
}

      

Simple enough, but the json / xml GET request returns empty.

I find it hard to believe that there is no easy way to change the answer without using ObjectMarshallers or converters?

+3


source to share


1 answer


I've dealt with this problem and also found there is a very useful plugin for customizing the marshalling / rendering behavior of Domain objects: " marshallers "

Keep in mind that for every domain you use the plugin with (by specifying "sorting" in the class), it will be dispensed with whatever settings you make in resources.groovy regarding your domain rendering. (This is actually a good thing IMHO, as it allows you to keep the rendering details about your domain class in the same place as the class.)



So your example Domain class would look like:

class DomainClassTest {
  static marshalling = {
    virtual {
        message { value, json -> json.value(value.getMessage()) }
    }
  }

  String foo
  String bar

  //add accessor
  String getMessage() {
      "Hello"
  }
}

      

+2


source







All Articles