Create object from Gson string doesn't work

Found the problem in the FModel there was indeed a 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 = new GsonBuilder()
                .registerTypeAdapter(Uri.class, new UriSerializer())
                .create();
        bdl.putString("oModel",gson.toJson(oModel));

and in the oncreate to rebuild this:

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

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();

You can also use TypeAdapter which is more efficient

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());
  }
}

Tags:

Json

Android

Gson