Search in sources :

Example 6 with JSONWriter

use of org.grails.web.json.JSONWriter in project grails-core by grails.

the class DomainClassMarshaller method marshalObject.

@SuppressWarnings({ "unchecked", "rawtypes" })
public void marshalObject(Object value, JSON json) throws ConverterException {
    JSONWriter writer = json.getWriter();
    value = proxyHandler.unwrapIfProxy(value);
    Class<?> clazz = value.getClass();
    List<String> excludes = json.getExcludes(clazz);
    List<String> includes = json.getIncludes(clazz);
    IncludeExcludeSupport<String> includeExcludeSupport = new IncludeExcludeSupport<String>();
    GrailsDomainClass domainClass = (GrailsDomainClass) application.getArtefact(DomainClassArtefactHandler.TYPE, ConverterUtil.trimProxySuffix(clazz.getName()));
    BeanWrapper beanWrapper = new BeanWrapperImpl(value);
    writer.object();
    if (includeClass && shouldInclude(includeExcludeSupport, includes, excludes, value, "class")) {
        writer.key("class").value(domainClass.getClazz().getName());
    }
    GrailsDomainClassProperty id = domainClass.getIdentifier();
    if (shouldInclude(includeExcludeSupport, includes, excludes, value, id.getName())) {
        Object idValue = extractValue(value, id);
        if (idValue != null) {
            json.property(GrailsDomainClassProperty.IDENTITY, idValue);
        }
    }
    if (shouldInclude(includeExcludeSupport, includes, excludes, value, GrailsDomainClassProperty.VERSION) && isIncludeVersion()) {
        GrailsDomainClassProperty versionProperty = domainClass.getVersion();
        Object version = extractValue(value, versionProperty);
        if (version != null) {
            json.property(GrailsDomainClassProperty.VERSION, version);
        }
    }
    GrailsDomainClassProperty[] properties = domainClass.getPersistentProperties();
    for (GrailsDomainClassProperty property : properties) {
        if (!shouldInclude(includeExcludeSupport, includes, excludes, value, property.getName()))
            continue;
        writer.key(property.getName());
        if (!property.isAssociation()) {
            // Write non-relation property
            Object val = beanWrapper.getPropertyValue(property.getName());
            json.convertAnother(val);
        } else {
            Object referenceObject = beanWrapper.getPropertyValue(property.getName());
            if (isRenderDomainClassRelations()) {
                if (referenceObject == null) {
                    writer.valueNull();
                } else {
                    referenceObject = proxyHandler.unwrapIfProxy(referenceObject);
                    if (referenceObject instanceof SortedMap) {
                        referenceObject = new TreeMap((SortedMap) referenceObject);
                    } else if (referenceObject instanceof SortedSet) {
                        referenceObject = new TreeSet((SortedSet) referenceObject);
                    } else if (referenceObject instanceof Set) {
                        referenceObject = new LinkedHashSet((Set) referenceObject);
                    } else if (referenceObject instanceof Map) {
                        referenceObject = new LinkedHashMap((Map) referenceObject);
                    } else if (referenceObject instanceof Collection) {
                        referenceObject = new ArrayList((Collection) referenceObject);
                    }
                    json.convertAnother(referenceObject);
                }
            } else {
                if (referenceObject == null) {
                    json.value(null);
                } else {
                    GrailsDomainClass referencedDomainClass = property.getReferencedDomainClass();
                    // Embedded are now always fully rendered
                    if (referencedDomainClass == null || property.isEmbedded() || property.getType().isEnum()) {
                        json.convertAnother(referenceObject);
                    } else if (property.isOneToOne() || property.isManyToOne() || property.isEmbedded()) {
                        asShortObject(referenceObject, json, referencedDomainClass.getIdentifier(), referencedDomainClass);
                    } else {
                        GrailsDomainClassProperty referencedIdProperty = referencedDomainClass.getIdentifier();
                        @SuppressWarnings("unused") String refPropertyName = referencedDomainClass.getPropertyName();
                        if (referenceObject instanceof Collection) {
                            Collection o = (Collection) referenceObject;
                            writer.array();
                            for (Object el : o) {
                                asShortObject(el, json, referencedIdProperty, referencedDomainClass);
                            }
                            writer.endArray();
                        } else if (referenceObject instanceof Map) {
                            Map<Object, Object> map = (Map<Object, Object>) referenceObject;
                            for (Map.Entry<Object, Object> entry : map.entrySet()) {
                                String key = String.valueOf(entry.getKey());
                                Object o = entry.getValue();
                                writer.object();
                                writer.key(key);
                                asShortObject(o, json, referencedIdProperty, referencedDomainClass);
                                writer.endObject();
                            }
                        }
                    }
                }
            }
        }
    }
    writer.endObject();
}
Also used : JSONWriter(org.grails.web.json.JSONWriter) BeanWrapperImpl(org.springframework.beans.BeanWrapperImpl) GrailsDomainClass(grails.core.GrailsDomainClass) GrailsDomainClassProperty(grails.core.GrailsDomainClassProperty) IncludeExcludeSupport(org.grails.core.util.IncludeExcludeSupport) BeanWrapper(org.springframework.beans.BeanWrapper) GroovyObject(groovy.lang.GroovyObject)

Example 7 with JSONWriter

use of org.grails.web.json.JSONWriter in project grails-core by grails.

the class EnumMarshaller method marshalObject.

public void marshalObject(Object en, JSON json) throws ConverterException {
    JSONWriter writer = json.getWriter();
    try {
        writer.object();
        Class<?> enumClass = en.getClass();
        json.property("enumType", enumClass.getName());
        Method nameMethod = BeanUtils.findDeclaredMethod(enumClass, "name", null);
        try {
            json.property("name", nameMethod.invoke(en));
        } catch (Exception e) {
            json.property("name", "");
        }
        writer.endObject();
    } catch (ConverterException ce) {
        throw ce;
    } catch (Exception e) {
        throw new ConverterException("Error converting Enum with class " + en.getClass().getName(), e);
    }
}
Also used : JSONWriter(org.grails.web.json.JSONWriter) ConverterException(org.grails.web.converters.exceptions.ConverterException) Method(java.lang.reflect.Method) ConverterException(org.grails.web.converters.exceptions.ConverterException)

Example 8 with JSONWriter

use of org.grails.web.json.JSONWriter in project grails-core by grails.

the class GroovyBeanMarshaller method marshalObject.

public void marshalObject(Object o, JSON json) throws ConverterException {
    JSONWriter writer = json.getWriter();
    Class<? extends Object> clazz = o.getClass();
    List<String> excludes = json.getExcludes(clazz);
    List<String> includes = json.getIncludes(clazz);
    IncludeExcludeSupport<String> includeExcludeSupport = new IncludeExcludeSupport<String>();
    try {
        writer.object();
        for (PropertyDescriptor property : BeanUtils.getPropertyDescriptors(clazz)) {
            Method readMethod = property.getReadMethod();
            String name = property.getName();
            if (!shouldInclude(includeExcludeSupport, includes, excludes, o, name))
                continue;
            if (readMethod != null && !(name.equals("metaClass")) && !(name.equals("class"))) {
                if (readMethod.getAnnotation(PersistenceMethod.class) != null)
                    continue;
                if (readMethod.getAnnotation(ControllerMethod.class) != null)
                    continue;
                Object value = readMethod.invoke(o, (Object[]) null);
                writer.key(name);
                json.convertAnother(value);
            }
        }
        for (Field field : clazz.getDeclaredFields()) {
            int modifiers = field.getModifiers();
            if (Modifier.isPublic(modifiers) && !(Modifier.isStatic(modifiers) || Modifier.isTransient(modifiers))) {
                String name = field.getName();
                if (!shouldInclude(includeExcludeSupport, includes, excludes, o, name))
                    continue;
                writer.key(name);
                json.convertAnother(field.get(o));
            }
        }
        writer.endObject();
    } catch (ConverterException ce) {
        throw ce;
    } catch (Exception e) {
        throw new ConverterException("Error converting Bean with class " + clazz.getName(), e);
    }
}
Also used : JSONWriter(org.grails.web.json.JSONWriter) ConverterException(org.grails.web.converters.exceptions.ConverterException) PropertyDescriptor(java.beans.PropertyDescriptor) ControllerMethod(grails.web.controllers.ControllerMethod) PersistenceMethod(grails.persistence.PersistenceMethod) Method(java.lang.reflect.Method) IncludeExcludeSupport(org.grails.core.util.IncludeExcludeSupport) ConverterException(org.grails.web.converters.exceptions.ConverterException) Field(java.lang.reflect.Field) PersistenceMethod(grails.persistence.PersistenceMethod) GroovyObject(groovy.lang.GroovyObject) ControllerMethod(grails.web.controllers.ControllerMethod)

Example 9 with JSONWriter

use of org.grails.web.json.JSONWriter in project grails-core by grails.

the class ValidationErrorsMarshaller method marshalObject.

public void marshalObject(Object object, JSON json) throws ConverterException {
    Errors errors = (Errors) object;
    JSONWriter writer = json.getWriter();
    try {
        writer.object();
        writer.key("errors");
        writer.array();
        for (Object o : errors.getAllErrors()) {
            if (o instanceof FieldError) {
                FieldError fe = (FieldError) o;
                writer.object();
                json.property("object", fe.getObjectName());
                json.property("field", fe.getField());
                json.property("rejected-value", fe.getRejectedValue());
                Locale locale = LocaleContextHolder.getLocale();
                if (applicationContext != null) {
                    json.property("message", applicationContext.getMessage(fe, locale));
                } else {
                    json.property("message", fe.getDefaultMessage());
                }
                writer.endObject();
            } else if (o instanceof ObjectError) {
                ObjectError fe = (ObjectError) o;
                writer.object();
                json.property("object", fe.getObjectName());
                Locale locale = LocaleContextHolder.getLocale();
                if (applicationContext != null) {
                    json.property("message", applicationContext.getMessage(fe, locale));
                } else {
                    json.property("message", fe.getDefaultMessage());
                }
                writer.endObject();
            }
        }
        writer.endArray();
        writer.endObject();
    } catch (ConverterException ce) {
        throw ce;
    } catch (Exception e) {
        throw new ConverterException("Error converting Bean with class " + object.getClass().getName(), e);
    }
}
Also used : JSONWriter(org.grails.web.json.JSONWriter) Locale(java.util.Locale) Errors(org.springframework.validation.Errors) ConverterException(org.grails.web.converters.exceptions.ConverterException) ObjectError(org.springframework.validation.ObjectError) FieldError(org.springframework.validation.FieldError) ConverterException(org.grails.web.converters.exceptions.ConverterException)

Aggregations

JSONWriter (org.grails.web.json.JSONWriter)9 ConverterException (org.grails.web.converters.exceptions.ConverterException)4 GroovyObject (groovy.lang.GroovyObject)3 Method (java.lang.reflect.Method)3 IncludeExcludeSupport (org.grails.core.util.IncludeExcludeSupport)3 PersistenceMethod (grails.persistence.PersistenceMethod)2 ControllerMethod (grails.web.controllers.ControllerMethod)2 PropertyDescriptor (java.beans.PropertyDescriptor)2 Field (java.lang.reflect.Field)2 GrailsDomainClass (grails.core.GrailsDomainClass)1 GrailsDomainClassProperty (grails.core.GrailsDomainClassProperty)1 EntityProxyHandler (grails.core.support.proxy.EntityProxyHandler)1 Locale (java.util.Locale)1 Map (java.util.Map)1 BeanWrapper (org.springframework.beans.BeanWrapper)1 BeanWrapperImpl (org.springframework.beans.BeanWrapperImpl)1 Errors (org.springframework.validation.Errors)1 FieldError (org.springframework.validation.FieldError)1 ObjectError (org.springframework.validation.ObjectError)1