9

我想确保杰克逊生成的 JSON 文件永远不会被打印出来。我是一个正在从事现有项目的初级人员,因此我需要向后工作以找出可以将 JSON 配置为输出为漂亮打印的所有方式。我可以确认项目中有 0 个对 .defaultPrettyPrintingWriter() 的引用,以及对 .setSerializationConfig 的 0 个引用,我相信它们也可以用于启用漂亮的打印。

那么这怎么可能呢?或者,是否有一种可靠的方法来确保 JSON 文件打印不美观?

4

3 回答 3

2

根据您使用的 Spring 版本,MappingJacksonHttpMessageConverte‌​r应该有一个布尔属性prettyPrint,用于在序列化 JSON 时配置打印机。

所以这个 XML 配置应该可以解决问题(如果您使用的是 Spring 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>

你可以在 github 上看到相关的 commit介绍该属性。还有这个类的主干版本,包括这个属性。最后,这是与先前提交相关的 Spring Jira 问题SPR-7201 。

或者您可以尝试将您的 Jackson 版本更新为更新的版本,其中包括Alexander Ryzhov 提到的useDefaultPrettyPrinter和方法setPrettyPrinter

于 2012-10-25T15:44:04.640 回答
1

最优雅的解决方案是将漂亮/非漂亮的开关放入过滤器中,并重用静态配置对象。这可以防止无用的垃圾收集。

/**
 * 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;
    }
  }
}
于 2017-12-19T08:16:44.363 回答
0

不确定您使用的是哪个版本的 Jackson,但在最新版本 (1.9.10) 中,JsonGenerator 的默认行为并不漂亮。打开它的最简单方法是调用generator.useDefaultPrettyPrinter()generator.setPrettyPrinter(new DefaultPrettyPrinter())。尝试搜索useDefaultPrettyPrintersetPrettyPrinter删除这些语句。

于 2012-10-25T06:31:05.500 回答