2012-08-07 1 views
6

Voglio assicurarmi che i file JSON generati da Jackson non siano mai abbastanza stampati. Sono un junior che lavora su un progetto preesistente, quindi ho bisogno di lavorare all'indietro per scoprire tutti i modi in cui JSON può essere configurato per produrre una bella stampa. Posso confermare che ci sono 0 riferimenti a .defaultPrettyPrintingWriter() nel progetto, così come 0 riferimenti a .setSerializationConfig, che credo possa essere usato anche per abilitare la stampa carina.Come impedire a Jackson di emettere una bella stampa JSON?

Quindi, in che altro modo è possibile? In alternativa, c'è un modo infallibile per garantire che il file JSON non sia una bella stampa?

+0

Si sta utilizzando un bean o un server applicazioni? Potresti voler controllare la proprietà 'prettyPrint' nei file di configurazione. –

+0

UPDATE: Ho trovato diverse istanze di ObjectMapper nel progetto su cui sto lavorando. Se ho scritto qualcosa come OutputMapper.configure (SerializationConfig.Feature.INDENT_OUTPUT, false); Poi otterrò il JSON di stampa non carina che sto cercando, giusto? – tamuren

+0

* "OutputMapper.configure (SerializationConfig.Feature.INDENT_OUTPUT, false); Quindi otterrò il JSON di stampa non carina che sto cercando, giusto?" ** In teoria, sì, questo dovrebbe rendere quell'istanza di ObjectMapper non bella stampa. Ci potrebbero essere comunque altri modi per creare ObjectMappers. –

risposta

2

A seconda della versione di Spring in uso, MappingJacksonHttpMessageConverte‌​r deve avere una proprietà booleana denominata prettyPrint per configurare la stampante durante la serializzazione di JSON.

Quindi questa configurazione XML dovrebbe fare il trucco (se si utilizza una versione recente di Primavera 3)

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAda‌​pter"> 
    <property name="messageConverters"> 
    <list> 
     <ref bean="jsonConverter" /> 
    </list> 
    </property> 
</bean> 

<bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverte‌​r"> 
    <property name="supportedMediaTypes" value="application/json" /> 
    <property name="objectMapper" ref="jacksonObjectMapper" /> 
    <property name="prettyPrint" value="false" /> 
</bean> 

si può vedere la related commit su github introduzione della proprietà. E anche lo trunk version della classe, che include questa proprietà. Finalmente questo è il problema Spring Jira SPR-7201 relativo al commit precedente.

Oppure si potrebbe provare ad aggiornare la versione di Jackson a uno più recente che include i metodi useDefaultPrettyPrinter e setPrettyPrinter come detto da Alexander Ryzhov

0

Non si sa quale versione di Jackson si sta usando, ma nell'ultima versione (1.9.10), il comportamento predefinito di JsonGenerator non è una bella stampa. Il modo più semplice per accenderlo è chiamare generator.useDefaultPrettyPrinter() o generator.setPrettyPrinter(new DefaultPrettyPrinter()). Prova a cercare useDefaultPrettyPrinter e setPrettyPrinter e rimuovere quelle dichiarazioni.

+0

La versione utilizzata da questo progetto è 1.3. Ho cercato il progetto per useDefaultPrettyPrinter e setPrettyPrinter, senza alcun risultato – tamuren

1

La soluzione più elegante è quella di mettere l'interruttore per la bella/non abbastanza in un filtro e riutilizzare oggetti di configurazione statici. Ciò impedisce inutili raccolte di dati inutili.

/** 
* Evaluate the "pretty" query parameter. If given without any value, or with "true": pretty JSON output. 
* E.g. /test?pretty or /test?pretty=true 
* Otherwise output without any formatting. 
* 
* @see https://stackoverflow.com/questions/10532217/jax-rs-json-pretty-output 
*/ 
@Provider 
@Produces(MediaType.APPLICATION_JSON) 
public class RestPrettyJsonFilter implements ContainerResponseFilter { 

    public static final String QUERYPARAM_PRETTY = "pretty"; 

    private static final IndentingModifier INDENTING_MODIFIER_PRETTY = new IndentingModifier(true); 
    private static final IndentingModifier INDENTING_MODIFIER_NOT_PRETTY = new IndentingModifier(false); 

    @Override 
    public void filter(ContainerRequestContext reqCtx, ContainerResponseContext respCtx) throws IOException { 

    boolean pretty = false; 

    UriInfo uriInfo = reqCtx.getUriInfo(); 
    //log.info("prettyFilter: "+uriInfo.getPath()); 

    MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters(); 
    if(queryParameters.containsKey(QUERYPARAM_PRETTY)) { 
     // Pretty query parameter is present 
     String prettyParam = queryParameters.getFirst(QUERYPARAM_PRETTY); 

     // Pretty is present without any value, or value is set to "true"? 
     if (prettyParam == null || "".equals(prettyParam) || "true".equals(prettyParam)) { 
     pretty = true; 
     } 
    } 

    // Prevent recreation of objects over and over again 
    //ObjectWriterInjector.set(new IndentingModifier(pretty)); 
    if (pretty) { 
     ObjectWriterInjector.set(INDENTING_MODIFIER_PRETTY); 
    } else { 
     ObjectWriterInjector.set(INDENTING_MODIFIER_NOT_PRETTY); 
    } 
    } 

    /** 
    * Used to switch on/off pretty output for each response. 
    */ 
    public static class IndentingModifier extends ObjectWriterModifier { 

    private final boolean indent; 

    /** Minimal pretty printer is not printing pretty. */ 
    private final static PrettyPrinter NOT_PRETTY_PRINTER = new com.fasterxml.jackson.core.util.MinimalPrettyPrinter(); 

    public IndentingModifier(boolean indent) { 
     this.indent = indent; 
    } 

    /* (non-Javadoc) 
    * @see com.fasterxml.jackson.jaxrs.cfg.ObjectWriterModifier#modify(com.fasterxml.jackson.jaxrs.cfg.EndpointConfigBase, javax.ws.rs.core.MultivaluedMap, java.lang.Object, com.fasterxml.jackson.databind.ObjectWriter, com.fasterxml.jackson.core.JsonGenerator) 
    */ 
    @Override 
    public ObjectWriter modify(EndpointConfigBase<?> endpointConfigBase, MultivaluedMap<String, Object> multivaluedMap, Object o, ObjectWriter objectWriter, JsonGenerator jsonGenerator) throws IOException { 
     if(indent) { 
     // Pretty 
     jsonGenerator.useDefaultPrettyPrinter(); 
     } else { 
     // Not pretty 
     jsonGenerator.setPrettyPrinter(NOT_PRETTY_PRINTER); 
     } 
     return objectWriter; 
    } 
    } 
}