本文介绍了在Jersey生成的JSON的末尾添加新行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基于Jersey(1.x)的REST服务.它使用Jackson 2.4.4生成JSON响应.我需要在响应末尾添加换行符(cURL用户抱怨响应中没有新行).我正在使用Jersey精美打印功能(SerializationFeature.INDENT_OUTPUT).

I have a Jersey (1.x) based REST service. It uses Jackson 2.4.4 to generate JSON responses. I need to add a newline character at the end of response (cURL users complain that there's no new line in responses). I am using Jersey pretty-print feature (SerializationFeature.INDENT_OUTPUT).

当前: {\n "prop" : "value"\n}

想要: {\n "prop" : "value"\n}\n

  1. 我尝试使用自定义序列化程序.我只需要在根对象的末尾添加\n.序列化程序是针对每种数据类型定义的,这意味着,如果此类的实例嵌套在响应中,则我将在JSON的中间获取\n.

  1. I tried using a custom serializer. I need to add \n only at the end of the root object. Serializer is defined per data type, which means, if an instance of such class is nested in a response, I will get \n in the middle of my JSON.

我想到了将com.fasterxml.jackson.core.JsonGenerator.java继承为子类,而在要添加writeRaw('\n')的地方重写close(),但这感觉很不客气.

I thought of subclassing com.fasterxml.jackson.core.JsonGenerator.java, overriding close() where i'd add writeRaw('\n'), but that feels very hacky.

另一个想法是添加Servlet过滤器,该过滤器将重写Jersey过滤器的响应,添加\n并将contentLenght递增1.效率也很低.

Another idea would be to add Servlet filter which would re-write the response from Jersey Filter, adding the \n and incrementing the contentLenght by 1. Seems not only hacky, but also inefficient.

我也可以放弃Jersey来负责序列化内容并执行ObjectMapper.writeValue() + "\n",但这对我的代码有很大的干扰(需要更改很多地方).

I could also give up Jersey taking care of serializing the content and do ObjectMapper.writeValue() + "\n", but this is quite intrusive to my code (need to change many places).

该问题的 clean 解决方案是什么?

What is the clean solution for that problem?

我发现了这些线程也遇到了同样的问题,但是它们都不提供解决方案:

I have found these threads for the same problem, but none of them provides solution:

  • http://markmail.org/message/nj4aqheqobmt4o5c
  • http://jackson-users.ning.com/forum/topics/add-newline-after-object-serialization-in-jersey

更新

最后,我使用NewlineAddingPrettyPrinter(也是Jackson的2.6.2版)寻求@arachnid的解决方案.遗憾的是,对于Jason作为 JAX-RS Json提供程序,它不能立即使用.在ObjectMapper中更改的PrettyPrinter不会传播到JsonGenerator(请参阅此处原因).为了使其正常工作,我必须添加ResponseFilter并添加ObjectWriterModifier(现在,我可以根据输入参数轻松在漂亮打印和最小打印量之间进行切换):

Finally I went for @arachnid's solution with NewlineAddingPrettyPrinter (also bumper Jackson version to 2.6.2). Sadly, it does not work out of the box with Jaskson as JAX-RS Json provider. Changed PrettyPrinter in ObjectMapper does not get propagated to JsonGenerator (see here why). To make it work, I had to add ResponseFilter which adds ObjectWriterModifier (now I can easily toggle between pretty-print and minimal, based on input param ):

@Provider
public class PrettyPrintFilter extends BaseResponseFilter {

    public ContainerResponse filter(ContainerRequest request, ContainerResponse response) {
        ObjectWriterInjector.set(new PrettyPrintToggler(true));
        return response;
    }

    final class PrettyPrintToggler extends ObjectWriterModifier {

        private static final PrettyPrinter NO_PRETTY_PRINT = new MinimalPrettyPrinter();

        private final boolean usePrettyPrint;

        public PrettyPrintToggler(boolean usePrettyPrint) {
            this.usePrettyPrint = usePrettyPrint;
        }

        @Override
        public ObjectWriter modify(EndpointConfigBase<?> endpoint, MultivaluedMap<String, Object> responseHeaders,
                                   Object valueToWrite, ObjectWriter w, JsonGenerator g) throws IOException {
            if (usePrettyPrint) g.setPrettyPrinter(new NewlineAddingPrettyPrinter());
            else g.setPrettyPrinter(NO_PRETTY_PRINT);
            return w;
        }

    }
}

推荐答案

实际上,包装(不是子类化)JsonGenerator也不是太糟糕:

Actually, wrapping up (not subclassing) JsonGenerator isn't too bad:

public static final class NewlineAddingJsonFactory extends JsonFactory {
    @Override
    protected JsonGenerator _createGenerator(Writer out, IOContext ctxt) throws IOException {
        return new NewlineAddingJsonGenerator(super._createGenerator(out, ctxt));
    }

    @Override
    protected JsonGenerator _createUTF8Generator(OutputStream out, IOContext ctxt) throws IOException {
        return new NewlineAddingJsonGenerator(super._createUTF8Generator(out, ctxt));
    }
}

public static final class NewlineAddingJsonGenerator extends JsonGenerator {
    private final JsonGenerator underlying;
    private int depth = 0;

    public NewlineAddingJsonGenerator(JsonGenerator underlying) {
        this.underlying = underlying;
    }

    @Override
    public void writeStartObject() throws IOException {
        underlying.writeStartObject();
        ++depth;
    }

    @Override
    public void writeEndObject() throws IOException {
        underlying.writeEndObject();
        if (--depth == 0) {
            underlying.writeRaw('\n');
        }
    }

    // ... and delegate all the other methods of JsonGenerator (CGLIB can hide this if you put in some time)
}


@Test
public void append_newline_after_end_of_json() throws Exception {
    ObjectWriter writer = new ObjectMapper(new NewlineAddingJsonFactory()).writer();
    assertThat(writer.writeValueAsString(ImmutableMap.of()), equalTo("{}\n"));
    assertThat(writer.writeValueAsString(ImmutableMap.of("foo", "bar")), equalTo("{\"foo\":\"bar\"}\n"));
}

尽管最近ServletOutputStream接口已被更多地用于正确拦截,但servlet过滤器也不一定太糟糕.

A servlet filter isn't necessarily too bad either, although recently the ServletOutputStream interface has been more involved to intercept properly.

我发现在Jackson早期版本(例如您的2.4.4)中通过PrettyPrinter执行此操作存在问题,部分原因是需要通过ObjectWriter对其进行正确配置:仅在Jackson 2.6中修复.为了完整起见,这是一个可行的2.5解决方案:

I found doing this via PrettyPrinter problematic on earlier Jackson versions (such as your 2.4.4), in part because of the need to go through an ObjectWriter to configure it properly: only fixed in Jackson 2.6. For completeness, this is a working 2.5 solution:

@Test
public void append_newline_after_end_of_json() throws Exception {
    // Jackson 2.6:
//      ObjectMapper mapper = new ObjectMapper()
//              .setDefaultPrettyPrinter(new NewlineAddingPrettyPrinter())
//              .enable(SerializationFeature.INDENT_OUTPUT);
//      ObjectWriter writer = mapper.writer();

    ObjectMapper mapper = new ObjectMapper();
    ObjectWriter writer = mapper.writer().with(new NewlineAddingPrettyPrinter());
    assertThat(writer.writeValueAsString(ImmutableMap.of()), equalTo("{}\n"));
    assertThat(writer.writeValueAsString(ImmutableMap.of("foo", "bar")),
            equalTo("{\"foo\":\"bar\"}\n"));
}

public static final class NewlineAddingPrettyPrinter
                    extends MinimalPrettyPrinter
                    implements Instantiatable<PrettyPrinter> {
    private int depth = 0;

    @Override
    public void writeStartObject(JsonGenerator jg) throws IOException, JsonGenerationException {
        super.writeStartObject(jg);
        ++depth;
    }

    @Override
    public void writeEndObject(JsonGenerator jg, int nrOfEntries) throws IOException, JsonGenerationException {
        super.writeEndObject(jg, nrOfEntries);
        if (--depth == 0) {
            jg.writeRaw('\n');
        }
    }

    @Override
    public PrettyPrinter createInstance() {
        return new NewlineAddingPrettyPrinter();
    }
}

这篇关于在Jersey生成的JSON的末尾添加新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 18:12