Custom HttpMessageConverter with @ResponseBody to

2020-01-24 11:14发布

I don't like Jackson.

I want to use ajax but with Google Gson.

So I'm trying to figure out how to implement my own HttpMessageConverter to use it with @ResponseBody annotation. Can someone take a time to show me the way I should go? What configurations should I turn on? Also I'm wondering if I can do this and still use <mvc:annotation-driven />?

Thanks in advance.

I've already asked it in Spring Community Foruns about 3 days ago with no answer so I'm asking here to see if I get a better chance. Spring Community Forums link to my question

I've also made an exhaustive search on the web and found something interesting on this subject but it seems they're thinking to put it in Spring 3.1 and I'm still using spring 3.0.5: Jira's Spring Improvement ask

Well... now I'm trying to debug Spring code to find out myself how to do this, but I'm having some problems like I've said here: Spring Framework Build Error

If there is another way to do this and I'm missing it, please let me know.

8条回答
放荡不羁爱自由
2楼-- · 2020-01-24 11:56

If you want to add a message converter without messing with xml here is a simple example

@Autowired
private RequestMappingHandlerAdapter adapter;

@PostConstruct
public void initStuff() {
    List<HttpMessageConverter<?>> messageConverters = adapter.getMessageConverters();
    BufferedImageHttpMessageConverter imageConverter = new BufferedImageHttpMessageConverter();;
    messageConverters.add(0,imageConverter);
}
查看更多
戒情不戒烟
3楼-- · 2020-01-24 11:57

Robby Pond is basically correct, but note that his suggestion to use the mvc:message-converters tag requires that you use 3.1. Since 3.1 is currently only a milestone release (M1), I'd suggest registering your converter this way after creating it:

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
      <util:list id="beanList">
        <ref bean="someMessageConverter"/>
        <ref bean="someOtherMessageConverter"/>
      </util:list>
    </property>
</bean>
查看更多
Explosion°爆炸
4楼-- · 2020-01-24 12:01

I had situation where usage of Jackson would require me to alter other group's (in the same company) code. Didn't like that. So I chose to use Gson and register TypeAdapters as needed.

Hooked up a converter and wrote a few integration tests using spring-test (used to be spring-mvc-test). No matter what variation I tried (using mvc:annotation-driven OR manual definition of the bean). None of them worked. Any combination of these always used the Jackson Converter which kept on failing.

Answer> Turns out that MockMvcBuilders' standaloneSetup method "hard" coded the message converters to default versions and ignored all my changes above. Here is what worked:

@Autowired
private RequestMappingHandlerAdapter adapter;

public void someOperation() {
  StandaloneMockMvcBuilder smmb = MockMvcBuilders.standaloneSetup(controllerToTest);
  List<HttpMessageConverter<?>> converters = adapter.getMessageConverters();
  HttpMessageConverter<?> ary[] = new HttpMessageConverter[converters.size()];
  smmb.setMessageConverters(conveters.toArray(ary));
  mockMvc = smmb.build();
   .
   .
}

Hope this helps someone, in the end I used annotation-driven and re-purposing android's converter

查看更多
来,给爷笑一个
5楼-- · 2020-01-24 12:07

You can do this by writing the WebConfig file as a Java File. Extend your config file with WebMvcConfigurerAdapter and override extendMessageConverters method to add your intented Message Convertor. This method will retain the default converters added by Spring and will add your convertor at the end. Apparently you have full control with the list and you can add where ever you want in the list.

@Configuration
@EnableWebMvc
@ComponentScan(basePackageClasses={WebConfig.class})
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
      converters.add(new GsonHttpMessageConverter());
   }
}

package net.iogui.web.spring.converter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.charset.Charset;

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.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

public class GsonHttpMessageConverter extends AbstractHttpMessageConverter<Object> {

private Gson gson = new Gson();

public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

public GsonHttpMessageConverter(){
    super(new MediaType("application", "json", DEFAULT_CHARSET));
}

@Override
protected Object readInternal(Class<? extends Object> clazz,
                              HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {

    try{
        return gson.fromJson(convertStreamToString(inputMessage.getBody()), clazz);
    }catch(JsonSyntaxException e){
        throw new HttpMessageNotReadableException("Could not read JSON: " + e.getMessage(), e);
    }

}

@Override
protected boolean supports(Class<?> clazz) {
    return true;
}

@Override
protected void writeInternal(Object t, 
                             HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {

    //TODO: adapt this to be able to receive a list of json objects too

    String json = gson.toJson(t);

    outputMessage.getBody().write(json.getBytes());
}

//TODO: move this to a more appropriated utils class
public String convertStreamToString(InputStream is) throws IOException {
    /*
     * To convert the InputStream to String we use the Reader.read(char[]
     * buffer) method. We iterate until the Reader return -1 which means
     * there's no more data to read. We use the StringWriter class to
     * produce the string.
     */
    if (is != null) {
        Writer writer = new StringWriter();

        char[] buffer = new char[1024];
        try {
            Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        } finally {
            is.close();
        }
        return writer.toString();
    } else {
        return "";
    }
}
查看更多
家丑人穷心不美
6楼-- · 2020-01-24 12:15

Notice that GsonHttpMessageConverter was added recently to Spring (4.1)

查看更多
Fickle 薄情
7楼-- · 2020-01-24 12:15

Or as mentioned in Jira's Spring Improvement ask, write a BeanPostProcessor that adds your HttpMessageConvertor to the AnnotationMethodHandlerAdapter

查看更多
登录 后发表回答