Last active
December 9, 2020 14:05
-
-
Save lucasmpavelski/cb15facb60bee9d9f7a55fad11baac46 to your computer and use it in GitHub Desktop.
Hibernate Validator's property name provider for Gson annotated classes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package util; | |
import java.util.Arrays; | |
import com.google.gson.annotations.Expose; | |
import com.google.gson.annotations.SerializedName; | |
import org.hibernate.validator.spi.nodenameprovider.JavaBeanProperty; | |
import org.hibernate.validator.spi.nodenameprovider.Property; | |
import org.hibernate.validator.spi.nodenameprovider.PropertyNodeNameProvider; | |
public class GsonPropertyNodeNameProvider implements PropertyNodeNameProvider { | |
@Override | |
public String getName(Property property) { | |
if (property instanceof JavaBeanProperty) { | |
String str = getJavaBeanPropertyName((JavaBeanProperty) property); | |
return str; | |
} | |
return getDefaultName(property); | |
} | |
private String getJavaBeanPropertyName(JavaBeanProperty property) { | |
return Arrays | |
.stream(property.getDeclaringClass().getDeclaredFields()) | |
.filter(f -> f.getName().equals(property.getName())) | |
.filter(f -> f.isAnnotationPresent(Expose.class)) | |
.filter(f -> f.getAnnotation(Expose.class).serialize()) | |
.filter(f -> f.isAnnotationPresent(SerializedName.class)) | |
.map(f -> f.getAnnotation(SerializedName.class).value()) | |
.findFirst() | |
.orElse(property.getName()); | |
} | |
private String getDefaultName(Property property) { | |
return property.getName(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment