読者です 読者をやめる 読者になる 読者になる

seratch's weblog in Japanese

About Scala, Java and Ruby programming in Japaense. If you need English information, go to http://blog.seratch.net/

Jersey(JAX-RS)で JSON レスポンスのキー名を snake_case にする方法

Java Jersey

もっといいやり方がありそうな気もしますが。

import org.codehaus.jackson.jaxrs.Annotations;
import org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.PropertyNamingStrategy;
import org.springframework.stereotype.Component;
 
import javax.ws.rs.ext.Provider;
 
/**
 * SnakeCaseJSONProvider
 */
@Component
@Provider
public class SnakeCaseJSONProvider extends JacksonJaxbJsonProvider {
 
    public SnakeCaseJSONProvider() {
        _mapperConfig.getDefaultMapper().setPropertyNamingStrategy(
          new PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy());
    }
 
    public SnakeCaseJSONProvider(ObjectMapper mapper, Annotations[] annotationsToUse) {
        super(mapper, annotationsToUse);
        mapper.setPropertyNamingStrategy(
          new PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy());
    }
 
}