Java tutorial
/* * Copyright 1999-2024 Colotnet.com All right reserved. This software is the confidential and proprietary information of * Colotnet.com ("Confidential Information"). You shall not disclose such Confidential Information and shall use it only * in accordance with the terms of the license agreement you entered into with Colotnet.com. */ package com.sunney.eweb.config; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.Charset; import org.apache.commons.io.output.ByteArrayOutputStream; import org.springframework.http.HttpInputMessage; import org.springframework.http.HttpOutputMessage; import org.springframework.http.MediaType; import org.springframework.http.converter.AbstractHttpMessageConverter; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.http.converter.HttpMessageNotWritableException; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; /** * MappingFastjson2HttpMessageConverter.java??TODO ?? * * @author Sunney 20161214 ?8:46:20 */ public class MappingFastjson2HttpMessageConverter extends AbstractHttpMessageConverter<Object> { public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); private SerializerFeature[] serializerFeature; public SerializerFeature[] getSerializerFeature() { return serializerFeature; } public void setSerializerFeature(SerializerFeature[] serializerFeature) { this.serializerFeature = serializerFeature; } public MappingFastjson2HttpMessageConverter() { super(new MediaType("application", "json", DEFAULT_CHARSET)); } @Override public boolean canRead(Class<?> clazz, MediaType mediaType) { return true; } @Override public boolean canWrite(Class<?> clazz, MediaType mediaType) { return true; } @Override protected boolean supports(Class<?> clazz) { throw new UnsupportedOperationException(); } @Override protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { @SuppressWarnings("resource") ByteArrayOutputStream baos = new ByteArrayOutputStream(); int i; while ((i = inputMessage.getBody().read()) != -1) { baos.write(i); } return JSON.parseArray(baos.toString(), clazz); } @Override protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { String jsonString = JSON.toJSONString(o, serializerFeature); OutputStream out = outputMessage.getBody(); out.write(jsonString.getBytes(DEFAULT_CHARSET)); out.flush(); } }