Created
January 3, 2024 18:36
-
-
Save jhaber/e84444c499fbf6f3a826246360cde657 to your computer and use it in GitHub Desktop.
This file contains 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
import com.fasterxml.jackson.core.Version; | |
import com.fasterxml.jackson.databind.BeanDescription; | |
import com.fasterxml.jackson.databind.Module; | |
import com.fasterxml.jackson.databind.SerializationConfig; | |
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter; | |
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier; | |
import java.util.ArrayList; | |
import java.util.Collections; | |
import java.util.List; | |
import java.util.Optional; | |
public class RandomPropertyOrderModule extends Module { | |
@Override | |
public String getModuleName() { | |
return getClass().getSimpleName(); | |
} | |
@Override | |
public Version version() { | |
return Version.unknownVersion(); | |
} | |
@Override | |
public void setupModule(SetupContext context) { | |
context.addBeanSerializerModifier(new RandomPropertyOrderBeanSerializerModifier()); | |
} | |
private static class RandomPropertyOrderBeanSerializerModifier | |
extends BeanSerializerModifier { | |
@Override | |
public List<BeanPropertyWriter> orderProperties( | |
SerializationConfig config, | |
BeanDescription beanDesc, | |
List<BeanPropertyWriter> beanProperties | |
) { | |
if (shouldSortAlphabetically(config, beanDesc)) { | |
return beanProperties; | |
} else { | |
beanProperties = new ArrayList<>(beanProperties); | |
Collections.shuffle(beanProperties); | |
return beanProperties; | |
} | |
} | |
} | |
private static boolean shouldSortAlphabetically( | |
SerializationConfig config, | |
BeanDescription beanDesc | |
) { | |
Optional<Boolean> sortAlphabetically = Optional.ofNullable( | |
config | |
.getAnnotationIntrospector() | |
.findSerializationSortAlphabetically(beanDesc.getClassInfo()) | |
); | |
return sortAlphabetically.orElseGet(config::shouldSortPropertiesAlphabetically); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment