从Gson字符串创建对象不起作用

时间:2022-09-15 12:32:22

I want to pass an object to a bundle. Now I did the conversion to a Json object with GSON.

我想将一个对象传递给一个包。现在我使用GSON转换为Json对象。

The bundle is passed, the bundle has the right string representation but when I create the object from the string I get a huge error.

bundle被传递,bundle有正确的字符串表示但是当我从字符串创建对象时,我得到一个巨大的错误。

FATAL EXCEPTION: main
    java.lang.RuntimeException: Failed to invoke private android.net.Uri() with no args
            at com.google.gson.internal.ConstructorConstructor$3.construct(ConstructorConstructor.java:107)
            at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:162)
            at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:93)
            at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:172)
            at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:40)
            at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:81)
            at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:60)
            at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:93)
            at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:172)
            at com.google.gson.Gson.fromJson(Gson.java:803)
            at com.google.gson.Gson.fromJson(Gson.java:768)
            at com.google.gson.Gson.fromJson(Gson.java:717)
            at com.google.gson.Gson.fromJson(Gson.java:689)
            at com.test.fragment.QFragment.onCreateView(QFragment.java:54)
            at android.app.Fragment.performCreateView(Fragment.java:1788)
            at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:899)
            at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1101)
            at android.app.BackStackRecord.run(BackStackRecord.java:688)
            at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1559)
            at android.app.FragmentManagerImpl$1.run(FragmentManager.java:445)
            at android.os.Handler.handleCallback(Handler.java:730)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:158)
            at android.app.ActivityThread.main(ActivityThread.java:5789)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:843)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.InstantiationException: can't instantiate class android.net.Uri
            at java.lang.reflect.Constructor.constructNative(Native Method)
            at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
            at com.google.gson.internal.ConstructorConstructor$3.construct(ConstructorConstructor.java:104)
            at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:162)
            at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:93)
            at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:172)
            at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:40)
            at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:81)
            at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:60)
            at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:93)
            at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:172)
            at com.google.gson.Gson.fromJson(Gson.java:803)
            at com.google.gson.Gson.fromJson(Gson.java:768)
            at com.google.gson.Gson.fromJson(Gson.java:717)
            at com.google.gson.Gson.fromJson(Gson.java:689)
            at com.test.fragment.QFragment.onCreateView(QFragment.java:54)
            at android.app.Fragment.performCreateView(Fragment.java:1788)
            at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:899)
            at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1101)
            at android.app.BackStackRecord.run(BackStackRecord.java:688)
            at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1559)
            at android.app.FragmentManagerImpl$1.run(FragmentManager.java:445)
            at android.os.Handler.handleCallback(Handler.java:730)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:158)
            at android.app.ActivityThread.main(ActivityThread.java:5789)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:843)
            at dalvik.system.NativeStart.main(Native Method)

I'm doing the conversion like this:

我正在做这样的转换:

public static QFragment newInstance(FModel oModel) {
    QFragment fragment = new QFragment();
    fragment.mOModel = oModel;
    Bundle bdl = new Bundle();
    bdl.putString("oModel", new Gson().toJson(oModel));
    fragment.setArguments(bdl);
    return fragment;
}

and in my fragment on the createView:

在我的createView片段中:

 String jsonMyObject = null;
        Bundle args = this.getArguments();
        if (args != null) {
            jsonMyObject = args.getString("oModel");
        }
        mOrderModel = new Gson().fromJson(jsonMyObject, FModel.class);

Whats the best way to fix this? Do I need to change to serializable or parcelable?

什么是解决这个问题的最佳方法?我是否需要更改为可序列化或可分割?

3 个解决方案

#1


23  

Found the problem in the FModel there was indeed a Uri.

在FModel中发现问题的确有一个Uri。

Solved this by writing:

通过写作解决这个问题:

public class UriSerializer implements JsonSerializer<Uri> {
    public JsonElement serialize(Uri src, Type typeOfSrc, JsonSerializationContext context) {
        return new JsonPrimitive(src.toString());
    }
}

public class UriDeserializer implements JsonDeserializer<Uri> {
    @Override
    public Uri deserialize(final JsonElement src, final Type srcType,
                           final JsonDeserializationContext context) throws JsonParseException {
        return Uri.parse(src.getAsString());
    }
}

and doing the Gson conversion like this:

并像这样进行Gson转换:

Gson gson = new GsonBuilder()
                .registerTypeAdapter(Uri.class, new UriSerializer())
                .create();
        bdl.putString("oModel",gson.toJson(oModel));

and in the oncreate to rebuild this:

并在oncreate重建这个:

Gson gson = new GsonBuilder()
                    .registerTypeAdapter(Uri.class, new UriDeserializer())
                    .create();
            jsonMyObject = args.getString("oModel");
            mOrderModel = gson.fromJson(jsonMyObject, FModel.class);

#2


14  

FYI, you can use serialize and deserialize at the same time by combining your two interfaces implementations into a single class.

仅供参考,您可以通过将两个接口实现组合到一个类中来同时使用序列化和反序列化。

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 {
    return Uri.parse(src.getAsString());
  }
}
....
new GsonBuilder()   
    .registerTypeAdapter(Uri.class, new UriInOut())
    .create();

#3


9  

You can also use TypeAdapter which is more efficient

您还可以使用效率更高的TypeAdapter

public final class UriAdapter extends TypeAdapter<Uri> {
  @Override 
  public void write(JsonWriter out, Uri uri) throws IOException {
    out.value(uri.toString());
  }

  @Override 
  public Uri read(JsonReader in) throws IOException {
    return Uri.parse(in.nextString());
  }
}

#1


23  

Found the problem in the FModel there was indeed a Uri.

在FModel中发现问题的确有一个Uri。

Solved this by writing:

通过写作解决这个问题:

public class UriSerializer implements JsonSerializer<Uri> {
    public JsonElement serialize(Uri src, Type typeOfSrc, JsonSerializationContext context) {
        return new JsonPrimitive(src.toString());
    }
}

public class UriDeserializer implements JsonDeserializer<Uri> {
    @Override
    public Uri deserialize(final JsonElement src, final Type srcType,
                           final JsonDeserializationContext context) throws JsonParseException {
        return Uri.parse(src.getAsString());
    }
}

and doing the Gson conversion like this:

并像这样进行Gson转换:

Gson gson = new GsonBuilder()
                .registerTypeAdapter(Uri.class, new UriSerializer())
                .create();
        bdl.putString("oModel",gson.toJson(oModel));

and in the oncreate to rebuild this:

并在oncreate重建这个:

Gson gson = new GsonBuilder()
                    .registerTypeAdapter(Uri.class, new UriDeserializer())
                    .create();
            jsonMyObject = args.getString("oModel");
            mOrderModel = gson.fromJson(jsonMyObject, FModel.class);

#2


14  

FYI, you can use serialize and deserialize at the same time by combining your two interfaces implementations into a single class.

仅供参考,您可以通过将两个接口实现组合到一个类中来同时使用序列化和反序列化。

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 {
    return Uri.parse(src.getAsString());
  }
}
....
new GsonBuilder()   
    .registerTypeAdapter(Uri.class, new UriInOut())
    .create();

#3


9  

You can also use TypeAdapter which is more efficient

您还可以使用效率更高的TypeAdapter

public final class UriAdapter extends TypeAdapter<Uri> {
  @Override 
  public void write(JsonWriter out, Uri uri) throws IOException {
    out.value(uri.toString());
  }

  @Override 
  public Uri read(JsonReader in) throws IOException {
    return Uri.parse(in.nextString());
  }
}