Hi al3c,
I expect this to be the same as Java,
Here is a sample program that illustrates the different behaviour in serialising in Java.
import static com.google.common.collect.Lists.newArrayList;
import java.util.List;
import com.google.gson.Gson;
public class Experiment {
public static void main(final String[] args) throws Exception {
final SubscriptionImpl subscription = new SubscriptionImpl("A");
subscription.setRecipients(newArrayList(new RecipientImpl("a@b"), new RecipientImpl("c@d")));
System.out.println(new Gson().toJson(newArrayList(subscription)));
}
interface Recipient {
String getEmail();
}
interface Subscription {
String getName();
List<Recipient> getRecipients();
}
static class RecipientImpl implements Recipient {
private final String email;
RecipientImpl(final String email) {
this.email = email;
}
@Override
public String getEmail() {
return email;
}
}
static class SubscriptionImpl implements Subscription {
private final String name;
private List<Recipient> recipients;
public SubscriptionImpl(final String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
@Override
public List<Recipient> getRecipients() {
return recipients;
}
public void setRecipients(final List<Recipient> recipients) {
this.recipients = recipients;
}
}
}
The above produced the following output:
> Task :Experiment.main()
[{"name":"A","recipients":[{"email":"a@b"},{"email":"c@d"}]}]
do you expect each element in the Json array to be different if the elements of the original list had different concrete types?
I’m inclined to say yes. The Java paradigm of implementing class deciding the actual behaviour of an interface kinda sorta extends to de/serialised values as well. Just as two concrete classes can have significantly different behaviour, they can have significantly different serialised notations too.
Of course, you can (and should!) write custom de/serialise handlers to handle such cases if they exist in your code. Gson offers hooks in the form of adapters and one of their uses is to handle such cases (however yucky).
(In my specific case there is only one implementation, not several)