Skip to content

Instantly share code, notes, and snippets.

@jhaber
Created January 3, 2024 18:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhaber/e84444c499fbf6f3a826246360cde657 to your computer and use it in GitHub Desktop.
Save jhaber/e84444c499fbf6f3a826246360cde657 to your computer and use it in GitHub Desktop.
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