Gson转换Json中Uri字符串

Posted by phantomVK on September 27, 2017

如果Json中有Uri字符串,需要自定义Gson的解释器:

先创建类UriDeserializer

public class UriInOut implements JsonSerializer<Uri>, JsonDeserializer<Uri> {

    @Override
    public JsonElement serialize(Uri src, Type typeOfSrc, JsonSerializationContext context) {
        return new JsonPrimitive(src.toString());
    }

    @Override
    public Uri deserialize(final JsonElement src, final Type srcType,
                           final JsonDeserializationContext context) throws JsonParseException {
        // Convert "https://phantomvk.com" to https://phantomvk.com
        return Uri.parse(src.toString().replace("\"", ""));
    }
}

最后构建Gson对象,并注册类型转换器UriDeserializer即可

Gson mGson = new GsonBuilder()
        .registerTypeAdapter(Uri.class, new UriInOut())
        .create();

参考链接: