我正在使用Spring MVC使用MappingJacksonHttpMessageConverter设置一个返回JSON对象的REST控制器。
如何告诉MappingJacksonHttpMessageConverter还在响应头上设置“Content-Length”属性? (默认情况下,“Content-Length”设置为-1,因为MappingJacksonHttpMessageConverter不计算JSON对象长度。)
我不在乎内容长度计算是否会影响控制器的响应时间(因为MappingJacksonHttpMessageConverter需要缓冲编组的JSON对象以计算其长度)。
此question was already asked,但未得到回答。
答案 0 :(得分:0)
使用我的MappingJsonHttpMessageConverter而不是MappingJacksonHttpMessageConverter在writeInternal中添加ByteArrayOutputStream和Content-length
package org.zcoreframework.web.http.converter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.SerializationFeature;
public class MappingJsonHttpMessageConverter extends MappingJackson2HttpMessageConverter {
@Override
protected void writeInternal(Object object, HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException {
JsonEncoding encoding = getJsonEncoding(outputMessage.getHeaders().getContentType());
// The following has been deprecated as late as Jackson 2.2 (April 2013);
// preserved for the time being, for Jackson 2.0/2.1 compatibility.
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
@SuppressWarnings("deprecation")
JsonGenerator jsonGenerator =
this.getObjectMapper().getJsonFactory().createJsonGenerator(byteArrayOutputStream, encoding);
// A workaround for JsonGenerators not applying serialization features
// https://github.com/FasterXML/jackson-databind/issues/12
if (this.getObjectMapper().isEnabled(SerializationFeature.INDENT_OUTPUT)) {
jsonGenerator.useDefaultPrettyPrinter();
}
try {
this.getObjectMapper().writeValue(jsonGenerator, object);
//--> set content length
outputMessage.getHeaders().setContentLength(byteArrayOutputStream.size());
byteArrayOutputStream.writeTo(outputMessage.getBody());
byteArrayOutputStream.flush();
}
catch (JsonProcessingException ex) {
throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
}
}
}