UserAuthoritySerializer.java 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package com.izouma.nineth.utils;
  2. import com.fasterxml.jackson.core.JsonGenerator;
  3. import com.fasterxml.jackson.core.JsonToken;
  4. import com.fasterxml.jackson.core.type.WritableTypeId;
  5. import com.fasterxml.jackson.databind.JsonSerializer;
  6. import com.fasterxml.jackson.databind.SerializerProvider;
  7. import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
  8. import com.izouma.nineth.security.Authority;
  9. import java.io.IOException;
  10. import java.util.HashSet;
  11. import java.util.Set;
  12. public class UserAuthoritySerializer extends JsonSerializer<Set<Authority>> {
  13. @Override
  14. public void serialize(Set<Authority> value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
  15. if (value == null) {
  16. gen.writeNull();
  17. } else {
  18. gen.writeStartArray();
  19. for (Authority authority : value) {
  20. gen.writeObject(authority);
  21. }
  22. gen.writeEndArray();
  23. }
  24. }
  25. @Override
  26. public void serializeWithType(Set<Authority> value, JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
  27. HashSet<Authority> set = new HashSet<>(value);
  28. WritableTypeId typeId = typeSer.writeTypePrefix(gen, typeSer.typeId(set, JsonToken.VALUE_STRING));
  29. gen.writeStartArray();
  30. for (Authority authority : set) {
  31. gen.writeObject(authority);
  32. }
  33. gen.writeEndArray();
  34. typeSer.writeTypeSuffix(gen, typeId);
  35. }
  36. }