Grails: JSONP callback without id and class in JSON file

I am working on a REST interface where people get a json file. The client must access the file from another domain. I am using jsonp, which still works. My problem is rendering in Grails. I am currently using "as JSON" to sort the object:

render "${params.jsoncallback}(${user as JSON})"

Access to the client of the Json file includes all attributes, including id and the class that I do not want to have there. If this is not jsonp, I do it so that works fine:

render(contentType:'text/json'){
   userName  user.userName
   userImage user.userImage
    :
    :
}

So, how do I get the id and class attributes from json when rendering "user as JSON"? Any idea?

Best regards, Klaas

+3
3

JSON, ObjectMarshaller.

// CustomDomainMarshaller.groovy in src/groovy:
import grails.converters.JSON;
import org.codehaus.groovy.grails.web.converters.ConverterUtil;
import org.codehaus.groovy.grails.web.converters.exceptions.ConverterException;
import org.codehaus.groovy.grails.web.converters.marshaller.ObjectMarshaller;
import org.codehaus.groovy.grails.web.json.JSONWriter;
import org.springframework.beans.BeanUtils;

public class CustomDomainMarshaller implements ObjectMarshaller<JSON> {

    static EXCLUDED = ['metaClass','class','id','version']

    public boolean supports(Object object) {
        return ConverterUtil.isDomainClass(object.getClass());
    }

    public void marshalObject(Object o, JSON json) throws ConverterException {
        JSONWriter writer = json.getWriter();
        try {
            writer.object();
            def properties = BeanUtils.getPropertyDescriptors(o.getClass());
            for (property in properties) {
                String name = property.getName();
                if(!EXCLUDED.contains(name)) {
                    def readMethod = property.getReadMethod();
                    if (readMethod != null) {
                        def value = readMethod.invoke(o, (Object[]) null);
                        writer.key(name);
                        json.convertAnother(value);
                    }
                }
            }
            writer.endObject();
        } catch (Exception e) {
            throw new ConverterException("Exception in CustomDomainMarshaller", e);
        }
    }
}

grails-app/conf/BootStrap.groovy:

class BootStrap {
   def init = { servletContext ->
      grails.converters.JSON.registerObjectMarshaller(new CustomDomainMarshaller())
   }
   def destroy = {}
}

Grails >= 1.1

+5

!

, , , . , "json" :

def userProfile = user.get(randomUser)

def jsonData = [
   : userProfile.userName,
  userimage: userProfile.userImage,
  userstreet: userProfile.userStreet,
  :
  :
] JSON

println jsonData​​p >

voila, json:)

+2

, JSON .

You can use FlexJSON , which allows you to exclude certain properties and transfer them to custom Codec . Also see here .

0
source

Source: https://habr.com/ru/post/1722317/


All Articles