new ObjectMapper().setPropertyNamingStrategy(new CstyleStrategy());
import
com.fasterxml.jackson.databind.PropertyNamingStrategy;
import
com.fasterxml.jackson.databind.cfg.MapperConfig;
import
com.fasterxml.jackson.databind.introspect.AnnotatedField;
import
com.fasterxml.jackson.databind.introspect.AnnotatedMethod;
public class CstyleStrategy extends
PropertyNamingStrategy {
private static final long serialVersionUID = 1L;
@Override
public String nameForField(final
MapperConfig<?> config, final AnnotatedField field, final String defaultName) {
return field.getName();
}
@Override
public String nameForGetterMethod(final
MapperConfig<?> config, final AnnotatedMethod method, final String defaultName) {
return convert(method, defaultName);
}
@Override
public String nameForSetterMethod(final
MapperConfig<?> config, final AnnotatedMethod method, final String defaultName) {
return convert(method, defaultName);
}
private String convert(final AnnotatedMethod method, final String input) {
final Class<?> clazz = method.getDeclaringClass();
final String className = clazz.getCanonicalName();
String result = null;
if (className.contains("mySpecialType")) {
StringBuilder resultBuffer = new StringBuilder();
for (int i = 0, len = input.length(); i < len; ++i) {
char c = input.charAt(i);
if (Character.isUpperCase(c)) {
resultBuffer.append('_');
c = Character.toLowerCase(c);
}
resultBuffer.append(c);
}
result = resultBuffer.toString();
} else {
result = input;
}
return result.toString();
}
}
|
No comments:
Post a Comment