Last active
September 30, 2020 16:53
-
-
Save almozavr/2aab84089b23cdf2d99d to your computer and use it in GitHub Desktop.
Parcelable helper to wrap object convertable with gson
This file contains 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
public class ObjectGsonParceler { | |
private final Gson gson; | |
public ObjectGsonParceler(Gson gson) { | |
this.gson = gson; | |
} | |
public Parcelable wrap(Object instance) { | |
try { | |
String json = encode(instance); | |
return new Wrapper(json); | |
} catch (IOException e) { | |
throw new RuntimeException(e); | |
} | |
} | |
public <T> T unwrap(Parcelable parcelable) { | |
Wrapper wrapper = (Wrapper) parcelable; | |
try { | |
return decode(wrapper.json); | |
} catch (IOException e) { | |
throw new RuntimeException(e); | |
} | |
} | |
private String encode(Object instance) throws IOException { | |
StringWriter stringWriter = new StringWriter(); | |
JsonWriter writer = new JsonWriter(stringWriter); | |
try { | |
Class<?> type = instance.getClass(); | |
writer.beginObject(); | |
writer.name(type.getName()); | |
gson.toJson(instance, type, writer); | |
writer.endObject(); | |
return stringWriter.toString(); | |
} finally { | |
writer.close(); | |
} | |
} | |
private <T> T decode(String json) throws IOException { | |
JsonReader reader = new JsonReader(new StringReader(json)); | |
try { | |
reader.beginObject(); | |
Class<?> type = Class.forName(reader.nextName()); | |
return gson.fromJson(reader, type); | |
} catch (ClassNotFoundException e) { | |
throw new RuntimeException(e); | |
} finally { | |
reader.close(); | |
} | |
} | |
private static class Wrapper implements Parcelable { | |
final String json; | |
Wrapper(String json) { | |
this.json = json; | |
} | |
@Override public int describeContents() { | |
return 0; | |
} | |
@Override public void writeToParcel(Parcel out, int flags) { | |
out.writeString(json); | |
} | |
public static final Creator<Wrapper> CREATOR = new Creator<Wrapper>() { | |
@Override public Wrapper createFromParcel(Parcel in) { | |
String json = in.readString(); | |
return new Wrapper(json); | |
} | |
@Override public Wrapper[] newArray(int size) { | |
return new Wrapper[size]; | |
} | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment