Java Clone Object Using GSON

I have to clone an object several times. My object is not serializable. I am using the following function

@SuppressWarnings("unchecked")
public static  T cloneThroughJson(T t) {
   Gson gson = new Gson();
   String json = gson.toJson(t);
   return (T) gson.fromJson(json, t.getClass());
}
// ...
Object cloned = cloneThroughJson(someObject);

I found that this returns every link to the same object. eg

Let's say first I will call it for cloneThroughJson(x) it returns Y I will call it again in the same function cloneThroughJson(x). And he returns again Y.

Do you know how to clone a non-serializable object in java using deep cloning?

+4
source share
1 answer

, . , . - .

:

Gson , , , , , ,

private class MoneyInstanceCreator implements InstanceCreator<Money> {
  public Money createInstance(Type type) {
    return new Money("1000000", CurrencyCode.USD);
  }
}

  • , .
  • , Id , .
+1

All Articles