Mostafa Hassan
Mostafa Hassan

Reputation: 298

Jackson encode all properties to base64

I have more than one class that I want to serialize using Jackson to generate Json, for example

public class A{
  int id;
  String name;
  Object database;
  ... getter and setter
}

I need to encode all value of the json to base64, so I configure the object mapper like this

public class Base64Serializer<T> extends StdSerializer<T> {

    private static final long serialVersionUID = 1L;

    protected Base64Serializer(Class<?> t, boolean f) {
        super(t, f);
    }

    @Override
    public void serialize(T value, JsonGenerator jsonGenerator, SerializerProvider arg2) throws IOException {
        String ecnodedOutput = Base64.getEncoder().encodeToString(((String) value).getBytes());
        jsonGenerator.writeString(ecnodedOutput);
    }
}

//Using the base64 Serializer to configure Object mapper 
    SimpleModule module = new SimpleModule();
    module.addSerializer(new Base64Serializer(String.class, false));
    objectMapper.registerModule(module);
    objectMapper.writerWithDefaultPrettyPrinter().writeValue(outputStream,intanceOfClassA);

The problem is it's only encode the String type as the serializer only accept one type, is there any method to encode all field values, (long, int, object, etc..) I mean to encode all value of the json field regarding it type of string or int??

Upvotes: 2

Views: 2086

Answers (2)

Ady
Ady

Reputation: 702

Just in case if someone is looking for converting any kind of object to Base64 string using something like Jackson or Gson. You could do something like this:

  1. Convert your object to string using Jackson/Gson:

    str = objectMapper.writeValueAsString(obj) OR str = gson.toJson(obj)

  2. Now you get bytes from your string using

    base64str = str.getBytes()

  3. Use java's Base64 class to convert bytes to Base64 string:

    Base64.getEncoder().encodeToString(base64str)

Upvotes: 0

i.bondarenko
i.bondarenko

Reputation: 3572

You could use following:

Serializer

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Base64;

public class Base64Serializer<T extends Serializable> extends StdSerializer<T> {

    private static final long serialVersionUID = 1L;

    protected Base64Serializer(Class<?> t, boolean f) {
        super(t, f);
    }

    @Override
    public void serialize(T value, JsonGenerator jsonGenerator, SerializerProvider arg2) throws IOException {
        String ecnodedOutput = Base64.getEncoder().encodeToString(serialize(value));
        jsonGenerator.writeString(ecnodedOutput);
    }

    public static byte[] serialize(Object obj) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ObjectOutputStream os = new ObjectOutputStream(out);
        os.writeObject(obj);
        return out.toByteArray();
    }
}

Registration and test:

 public class SerializerTest {
    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        SimpleModule module = new SimpleModule();
        addSerializers(module, Serializable.class, int.class, double.class, float.class, char.class, byte.class, short.class);
        objectMapper.registerModule(module);
        System.out.println(objectMapper.writeValueAsString(new A(10, "test", Arrays.asList(10000L, "TTTT2"))));
    }

    private static void addSerializers(SimpleModule module, Class... classes) {
        Arrays.stream(classes).forEach(c -> module.addSerializer(new Base64Serializer(c, false)));
    }
}

Output:

{
  "id": "rO0ABXNyABFqYXZhLmxhbmcuSW50ZWdlchLioKT3gYc4AgABSQAFdmFsdWV4cgAQamF2YS5sYW5nLk51bWJlcoaslR0LlOCLAgAAeHAAAAAK",
  "name": "rO0ABXQABHRlc3Q=",
  "database": "rO0ABXNyABpqYXZhLnV0aWwuQXJyYXlzJEFycmF5TGlzdNmkPL7NiAbSAgABWwABYXQAE1tMamF2YS9sYW5nL09iamVjdDt4cHVyABdbTGphdmEuaW8uU2VyaWFsaXphYmxlO67QCaxT1+1JAgAAeHAAAAACc3IADmphdmEubGFuZy5Mb25nO4vkkMyPI98CAAFKAAV2YWx1ZXhyABBqYXZhLmxhbmcuTnVtYmVyhqyVHQuU4IsCAAB4cAAAAAAAACcQdAAFVFRUVDI="
}

Upvotes: 2

Related Questions