Created
May 21, 2017 05:33
-
-
Save elucash/ee4d294cb0d920fc227d993aebf6d53c to your computer and use it in GitHub Desktop.
byte[] base64 encoder for Gson (showcase)
This file contains hidden or 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
package sample; | |
import com.google.gson.GsonBuilder; | |
import com.google.gson.TypeAdapter; | |
import com.google.gson.stream.JsonReader; | |
import com.google.gson.stream.JsonWriter; | |
import java.io.IOException; | |
import java.util.Base64; | |
import org.immutables.gson.Gson; | |
import org.immutables.value.Value; | |
@Gson.TypeAdapters | |
@Value.Immutable | |
public abstract class Document { | |
public abstract byte[] raw(); | |
public static void main(String... args) { | |
com.google.gson.Gson gson = | |
new GsonBuilder() | |
.registerTypeAdapterFactory(new GsonAdaptersDocument()) | |
.registerTypeAdapter(byte[].class, new Base64TypeAdapter()) | |
.create(); | |
String json = | |
gson.toJson(ImmutableDocument.builder() | |
.raw(new byte[] {1, 2, 3, 4, 5}) | |
.build()); | |
System.out.println(json); | |
// {"raw":"AQIDBAU"} | |
Document document = gson.fromJson(json, ImmutableDocument.class); | |
System.out.println(document); | |
// Document{raw=[1, 2, 3, 4, 5]} | |
} | |
public static class Base64TypeAdapter extends TypeAdapter<byte[]> { | |
@Override | |
public void write(JsonWriter out, byte[] value) throws IOException { | |
out.value(Base64.getEncoder().withoutPadding().encodeToString(value)); | |
} | |
@Override | |
public byte[] read(JsonReader in) throws IOException { | |
return Base64.getDecoder().decode(in.nextString()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment