Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Gson type adapter to serialize and deserialize byte arrays in base64
import java.lang.reflect.Type;
import android.util.Base64;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
public class GsonHelper {
public static final Gson customGson = new GsonBuilder().registerTypeHierarchyAdapter(byte[].class,
new ByteArrayToBase64TypeAdapter()).create();
// Using Android's base64 libraries. This can be replaced with any base64 library.
private static class ByteArrayToBase64TypeAdapter implements JsonSerializer<byte[]>, JsonDeserializer<byte[]> {
public byte[] deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return Base64.decode(json.getAsString(), Base64.NO_WRAP);
}
public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(Base64.encodeToString(src, Base64.NO_WRAP));
}
}
}
@jlccaires

This comment has been minimized.

Copy link

commented Nov 27, 2013

Great!

@francesco-strazzullo

This comment has been minimized.

Copy link

commented Feb 5, 2014

Thanks!

@codertimu

This comment has been minimized.

Copy link

commented Jun 9, 2014

very useful. thanks.

@kiumars

This comment has been minimized.

Copy link

commented Sep 18, 2014

Thanks great help

@JiboStore

This comment has been minimized.

Copy link

commented Jun 30, 2015

how do I serialize and deserialize?
I use:
customGson.toJson(jsonObject, osw);
and:
result = customGson.fromJson(reader, type);
however, the serialize and deserialize functions are not called and I am still getting the serialized output in pretty json string format

@jan4984

This comment has been minimized.

Copy link

commented Mar 23, 2016

👍

@SungJinYoo

This comment has been minimized.

Copy link

commented Mar 28, 2016

thanks very much

@bpgriner

This comment has been minimized.

Copy link

commented Jan 27, 2017

@JiboStore

You can register typeAdapters like so:

GsonBuilder builder = new GsonBuilder();

// Adapter to convert a Unix Long Time in Json to a java.util.Date object
builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
    public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        return new Date(json.getAsJsonPrimitive().getAsLong());
    }
});

// Adapter to convert byte[] in a Java Object to a String in Json for UI to display image properly
builder.registerTypeAdapter(byte[].class, new JsonSerializer<byte[]>() {
    public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) {
        return new JsonPrimitive(Base64.getEncoder().encodeToString(src));
    }
});

Gson gson = builder.create();

And then to use:

// Deserialize | You have a Json string with a Unix Long Time and you want to convert to a Date object inside YourJavaObject
YourJavaObject obj = gson.fromJson(jsonStringHere, YourJavaObject.class);

// Serialize | YourJavaObject has a byte[] and you want to convert it to a String in your Json
String json = gson.toJson(yourJavaObjectHere);
@DamianoPantani

This comment has been minimized.

Copy link

commented Feb 14, 2017

Thank you. Using org.apache.commons.codec.binary.Base64 this methods seems to be working:

@Override
public byte[] deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
	return Base64.decodeBase64(json.getAsString());
}

@Override
public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) {
	return new JsonPrimitive(Base64.encodeBase64String(src));
}
@pupeno

This comment has been minimized.

Copy link

commented Aug 29, 2017

Using Java 1.8, with Lambdas, I have serialization a deserialization of byte arrays to Base64 with this code:

GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(byte[].class, (JsonSerializer<byte[]>) (src, typeOfSrc, context) -> new JsonPrimitive(Base64.getEncoder().encodeToString(src)));
builder.registerTypeAdapter(byte[].class, (JsonDeserializer<byte[]>) (json, typeOfT, context) -> Base64.getDecoder().decode(json.getAsString()));
Gson gson = builder.create();
@bahcetepe

This comment has been minimized.

Copy link

commented Aug 17, 2018

thank you so much.

@deois

This comment has been minimized.

Copy link

commented Apr 12, 2019

thank you!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.