Hi guys and thanks for the hard work.
It might be great to have an optional fallback value on the PolymorphicJsonAdapterFactory.
What do you think of that?
Thanks!
Seems reasonable to me. Document that it's shared and should be an immutable value.
I had to implement two additional cases: when subtype flag/label is missing (requirement) or unknown subclass is met and base subclass should be used. I can contribute if you find those cases useful for others.
Builder has additional method withDefaultSubtype that disables exception throwing when unrecognised label is found and initialises instance of type passed as argument.
Builder has additional method withFallbackSubtype that disables exception throwing when type label is missing and initialises instance of type passed as argument.
Now I think my code is a slight extension of https://github.com/square/moshi/pull/741 but fallback for missing label still might be useful.
Nice, sounds good to me.
The PR #778 does a great job when it meets an enum(although I haven't test it) but it needs to do more to work with subtypes.
This piece of code is from the PR
@Override public Object fromJson(JsonReader reader) throws IOException {
int labelIndex = labelIndex(reader.peekJson());
if (labelIndex == -1) {
reader.skipValue();
return defaultValue;
}
return jsonAdapters.get(labelIndex).fromJson(reader);
}
To support withDefaultSubtype or withFallbackSubtype, our intelligent PolymorphicJsonAdapterFactory needs to accept a sub type json adapter and do something like this:
@Override public Object fromJson(JsonReader reader) throws IOException {
int labelIndex = labelIndex(reader.peekJson());
if (labelIndex == -1) {
reader.skipValue();
// This line
return defaultJsonAdapter.fromJson(reader);
}
return jsonAdapters.get(labelIndex).fromJson(reader);
}
@DeweyReed is this a feature request or a bug report? Can you create a new issue?
@swankjesse I notice someone mentioned withDefaultSubtype and withFallbackSubtype but the PR doesn't provide similar functions. I just created a new issue #784.
Most helpful comment
I had to implement two additional cases: when subtype flag/label is missing (requirement) or unknown subclass is met and base subclass should be used. I can contribute if you find those cases useful for others.
Builder has additional method
withDefaultSubtypethat disables exception throwing when unrecognised label is found and initialises instance of type passed as argument.Builder has additional method
withFallbackSubtypethat disables exception throwing when type label is missing and initialises instance of type passed as argument.Now I think my code is a slight extension of https://github.com/square/moshi/pull/741 but fallback for missing label still might be useful.