如何防止杰克逊输出漂亮的打印JSON?

时间:2022-02-11 01:59:22

I want to make sure that the JSON files generated by Jackson are never pretty print. I'm a junior working on a pre-existing project, so I need to work backwards to find out all the ways that JSON can be configured to output as pretty print. I can confirm there are 0 references to .defaultPrettyPrintingWriter() in the project, as well as 0 references to .setSerializationConfig, which I believe may also be used to enable pretty print.

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

So how else is this possible? Alternatively, is there a sure-fire way to ensure the JSON file is not pretty print?

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

3 个解决方案

#1


2  

Depending on what version of Spring you are using the MappingJacksonHttpMessageConverte‌​r should have a boolean property named prettyPrint to configure the printer when serializing JSON.

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

So this XML configuration should do the trick (if you are using a recent version of Spring 3)

所以这个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>

You can see the related commit on github introducing the property. And the trunk version of the class too, that includes this property. Finally this is the Spring Jira issue SPR-7201 related to the previous commit.

您可以在github上看到引入该属性的相关提交。并且类的主干版本也包含此属性。最后这是与前一次提交相关的Spring Jira问题SPR-7201。

Or you could try to update your version of Jackson to a more recent one that includes the useDefaultPrettyPrinter and setPrettyPrinter methods as mentioned by Alexander Ryzhov

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

#2


1  

The most elegant solution is to put the switch for pretty/non-pretty into a filter, and reuse static configuration objects. This prevents useless garbage collections.

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

/**
 * 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://*.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;
    }
  }
}

#3


0  

Not sure which version of Jackson you are using but in the latest version (1.9.10), the default behavior of JsonGenerator is no pretty print. The easiest way to turn it on is to call generator.useDefaultPrettyPrinter() or generator.setPrettyPrinter(new DefaultPrettyPrinter()). Try searching for useDefaultPrettyPrinter and setPrettyPrinter and remove those statements.

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

#1


2  

Depending on what version of Spring you are using the MappingJacksonHttpMessageConverte‌​r should have a boolean property named prettyPrint to configure the printer when serializing JSON.

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

So this XML configuration should do the trick (if you are using a recent version of Spring 3)

所以这个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>

You can see the related commit on github introducing the property. And the trunk version of the class too, that includes this property. Finally this is the Spring Jira issue SPR-7201 related to the previous commit.

您可以在github上看到引入该属性的相关提交。并且类的主干版本也包含此属性。最后这是与前一次提交相关的Spring Jira问题SPR-7201。

Or you could try to update your version of Jackson to a more recent one that includes the useDefaultPrettyPrinter and setPrettyPrinter methods as mentioned by Alexander Ryzhov

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

#2


1  

The most elegant solution is to put the switch for pretty/non-pretty into a filter, and reuse static configuration objects. This prevents useless garbage collections.

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

/**
 * 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://*.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;
    }
  }
}

#3


0  

Not sure which version of Jackson you are using but in the latest version (1.9.10), the default behavior of JsonGenerator is no pretty print. The easiest way to turn it on is to call generator.useDefaultPrettyPrinter() or generator.setPrettyPrinter(new DefaultPrettyPrinter()). Try searching for useDefaultPrettyPrinter and setPrettyPrinter and remove those statements.

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