Look on the next flow i have done
public class SomeClass {
private int x;
private Object object;
public SomeClass(Object object) {
this.object = object;
}
}
public class AnotherClass {
private String test;
private int y;
public AnotherClass() {
test = "dsadas";
y = 5;
}
}
When i am doing the next:
gson.toJson(new SomeClass(new AnotherClass()));
The result is: {"x":0,"object":{"test":"dsadas","y":5}}
As you can see it works fine this way
EDIT:
In case of deserialization there is a known issues and handling with this situation.
The problem that gson don't know what to convert the json to.. So you have to send in gson the type you want to parse it too and build deserizaler.
What is more common is to create Interface for this other class.. So you can mark it. Let's say IOtherClass
Now one of the fields for IOtherClass will be the TYPE.
You need to build deseriaze for IOtherClass, and there you will make the conversion according to the type.
This is the only way to tell gson what to parse to
Look on this thread: How to handle deserializing with polymorphism?
And this one: Gson serialize a list of polymorphic objects