2012-04-17 8 views
8

Sto cercando di registrare un marshaller JSON personalizzato come questocome registrare un JSON marshaller personalizzato in graal

JSON.createNamedConfig("dynamic",{ 
      def m = new CustomJSONSerializer() 
      JSON.registerObjectMarshaller(Idf, 1, { instance, converter -> m.marshalObject(instance, converter) }) 
      }) 

and then using it like this 

    JSON.use("dynamic"){ 
      render inventionList as JSON 
      } 

ma non sono sicuro se è in uso la mia serializzatore personalizzato perché quando sono il debug di controllo mai va a marshalObject funzione della mia serializzatore personalizzato

mio serializzatore personalizzato è la seguente

import grails.converters.deep.JSON 
import java.beans.PropertyDescriptor 
import java.lang.reflect.Field 
import java.lang.reflect.Method 
import org.codehaus.groovy.grails.web.converters.exceptions.ConverterException 
import org.codehaus.groovy.grails.web.converters.marshaller.json.GroovyBeanMarshaller 
import org.codehaus.groovy.grails.web.json.JSONWriter 

class CustomJSONSerializer extends GroovyBeanMarshaller{ 
    public boolean supports(Object object) { 
     return object instanceof GroovyObject; 
    } 

    public void marshalObject(Object o, JSON json) throws ConverterException { 
     JSONWriter writer = json.getWriter(); 
     println 'properties '+BeanUtils.getPropertyDescriptors(o.getClass()) 
     for(PropertyDescriptor property:BeanUtils.getProperyDescriptors(o.getClass())){ 
       println 'property '+property.getName() 
      } 
     try { 
      writer.object(); 
      for (PropertyDescriptor property : BeanUtils.getPropertyDescriptors(o.getClass())) { 
       String name = property.getName(); 
       Method readMethod = property.getReadMethod(); 
       if (readMethod != null && !(name.equals("metaClass")) && readMethod.getName()!='getSpringSecurityService') { 
        Object value = readMethod.invoke(o, (Object[]) null); 
        writer.key(name); 
        json.convertAnother(value); 
       } 
      } 
      for (Field field : o.getClass().getDeclaredFields()) { 
       int modifiers = field.getModifiers(); 
       if (Modifier.isPublic(modifiers) && !(Modifier.isStatic(modifiers) || Modifier.isTransient(modifiers))) { 
        writer.key(field.getName()); 
        json.convertAnother(field.get(o)); 
       } 
      } 
      writer.endObject(); 
     } 
     catch (ConverterException ce) { 
      throw ce; 
     } 
     catch (Exception e) { 
      throw new ConverterException("Error converting Bean with class " + o.getClass().getName(), e); 
     } 
    } 


} 

E 'possibile eseguire il debug le s erializer? Altrimenti, come posso escludere una proprietà dalla serializzazione? C'è una proprietà che genera un'eccezione durante la serializzazione.

+0

ho risolto importando alcuni file mancanti come BeanUtils e modificatore –

risposta

9

questo è quello che faccio per JSON personalizzato marshalling nella chiusura init Bootstrap:

def init = {servletContext -> 
    grailsApplication.domainClasses.each {domainClass -> 
     domainClass.metaClass.part = {m -> 
      def map = [:] 
      if (m.'include') { 
       m.'include'.each { 
        map[it] = delegate."${it}" 
       } 
      } else if (m.'except') { 
       m.'except'.addAll excludedProps 
       def props = domainClass.persistentProperties.findAll { 
        !(it.name in m.'except') 
       } 
       props.each { 
        map['id'] = delegate.id 
        map[it.name] = delegate."${it.name}" 
       } 
      } 
      return map 
     } 



    } 
    JSON.registerObjectMarshaller(Date) { 
     return it?.format("dd.MM.yyyy") 
    } 
    JSON.registerObjectMarshaller(User) { 
     def returnArray = [:] 
     returnArray['username'] = it.username 
     returnArray['userRealName'] = it.userRealName 
     returnArray['email'] = it.email 
     return returnArray 
    } 
    JSON.registerObjectMarshaller(Role) { 
     def returnArray = [:] 
     returnArray['authority'] = it.authority 
     return returnArray 
    } 
    JSON.registerObjectMarshaller(Person) { 
     return it.part(except: ['fieldX', 'fieldY']) 
    }} 

si vede che ho marshaller personalizzati per la data, utilizzare, una persona, e Classe ruolo

6

ho trovato questo post durante il tentativo di trovare un modo corretto per la registrazione del marshaller. La più grande differenza rispetto alla risposta di Nils è che questa soluzione lascia intatto BootStrap.groovy, che è bello.

http://compiledammit.com/2012/08/16/custom-json-marshalling-in-grails-done-right/

+1

L'articolo che collegato a un approccio molto migliore e più pulito. Per aiutare a gestire il link rot, ti preghiamo di prendere in considerazione le parti più rilevanti dell'articolo qui nella tua risposta. Il sito – cdeszaq

+0

sembra essere inattivo in questi giorni. – adeady

Problemi correlati