Last active
April 9, 2024 09:54
-
-
Save ypresto/3607f395ac4ef2921a8de74e9a243629 to your computer and use it in GitHub Desktop.
Gson adapter for Android's Uri class.
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
import android.net.Uri; | |
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; | |
import java.lang.reflect.Type; | |
/** | |
* Serialize/Deserialize Android's {@link Uri} class. | |
* You can register this by | |
* `{@code registerTypeHierarchyAdapter(Uri.class, new UriTypeHierarchyAdapter())}'. | |
*/ | |
// https://gist.github.com/ypresto/3607f395ac4ef2921a8de74e9a243629 | |
public class UriTypeHierarchyAdapter implements JsonDeserializer<Uri>, JsonSerializer<Uri> { | |
@Override | |
public Uri deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { | |
return Uri.parse(json.getAsString()); | |
} | |
@Override | |
public JsonElement serialize(Uri src, Type typeOfSrc, JsonSerializationContext context) { | |
// Note that Uri is abstract class. | |
return new JsonPrimitive(src.toString()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Modern Kotlin version: