1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| public class FastJsonHttpMessageConverter extends AbstractHttpMessageConverter<Object> { public final static Charset UTF8 = Charset.forName("UTF-8"); private Charset charset = UTF8; private SerializerFeature[] features = new SerializerFeature[0]; public FastJsonHttpMessageConverter(){ super(new MediaType("application", "json", UTF8), new MediaType("application", "*+json", UTF8)); } @Override protected boolean supports(Class<?> clazz) { return true; } public Charset getCharset() { return this.charset; } public void setCharset(Charset charset) { this.charset = charset; } public SerializerFeature[] getFeatures() { return features; } public void setFeatures(SerializerFeature... features) { this.features = features; } @Override protected Object readInternal(Class<? extends Object> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream in = inputMessage.getBody(); byte[] buf = new byte[1024]; for (;;) { int len = in.read(buf); if (len == -1) { break; } if (len > 0) { baos.write(buf, 0, len); } } byte[] bytes = baos.toByteArray(); return JSON.parseObject(bytes, 0, bytes.length, charset.newDecoder(), clazz); } @Override protected void writeInternal(Object obj, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { OutputStream out = outputMessage.getBody(); String text = JSONUtil.toJSONString(obj, features); byte[] bytes = text.getBytes(charset); out.write(bytes); } }
|