如果Json中有Uri字符串,需要自定义Gson的解释器:
先创建类UriDeserializer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
即可
1
2
3
Gson mGson = new GsonBuilder()
.registerTypeAdapter(Uri.class, new UriInOut())
.create();
参考链接: