无法使用Gson序列化Android.net.Uri

时间:2018-07-10 20:10:40

标签: android gson

当我尝试使用Gson序列化Android.net.Uri时,出现以下错误:

java.lang.IllegalArgumentException: class android.net.Uri$Part declares multiple JSON fields named __robo_data__

at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:170)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:100)
at com.google.gson.Gson.getAdapter(Gson.java:423)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:115)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:164)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:100)
at com.google.gson.Gson.getAdapter(Gson.java:423)
at com.google.gson.Gson.toJson(Gson.java:661)
at com.google.gson.Gson.toJson(Gson.java:648)
at com.google.gson.Gson.toJson(Gson.java:603)
at com.google.gson.Gson.toJson(Gson.java:583)

我尝试使用JsonSerializer,TypeAdapter,如下所示,但是它们都不起作用。有人知道解决方法吗?

public void getUriJson() {
    Uri uri = Uri.parse("https://www.google.com");
    GsonBuilder builder = new GsonBuilder();

    builder.registerTypeAdapter(Uri.class, new UriSerializer());
    String json = builder.create().toJson(uri);
}

private class UriSerializer implements JsonSerializer<Uri> {

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

注意:我不是要获取Uri的字符串。我的对象中有一个Uri字段,其中有很多字段。除uri外,所有这些都可以序列化。

0 个答案:

没有答案