-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Add support for new JsonTypeInfo.Id.SIMPLE_NAME polymorphic type id option
#4065
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
cowtowncoder
merged 11 commits into
FasterXML:2.16
from
JooHyukKim:4061-JsonTypeInfo.Id.SIMPLE_NAME-
Aug 26, 2023
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
9038a79
Implement with basic test
JooHyukKim 38f4952
Update JsonTypeInfoSimpleClassName4061Test.java
JooHyukKim 2ffd950
Merge remote-tracking branch 'upstream/2.16' into 4061-JsonTypeInfo.I…
JooHyukKim ebe04f5
`SimpleNameIdResolver` and `_defaultTypeId(cls);`
JooHyukKim 22bdd8f
Add more test cases
JooHyukKim 6cf8ad0
Add JavaDoc
JooHyukKim eae086e
Update JsonTypeInfoSimpleClassName4061Test.java
JooHyukKim cd39a4b
Remove additional Test class container and move dup class to same mai…
JooHyukKim 1e5e3cd
Make JavaDoc consistent
JooHyukKim ca9cb58
Merge branch '2.16' into 4061-JsonTypeInfo.Id.SIMPLE_NAME-
cowtowncoder f8d0d7c
Merge branch '2.16' into 4061-JsonTypeInfo.Id.SIMPLE_NAME-
cowtowncoder File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
205 changes: 205 additions & 0 deletions
205
src/main/java/com/fasterxml/jackson/databind/jsontype/impl/SimpleNameIdResolver.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,205 @@ | ||
| package com.fasterxml.jackson.databind.jsontype.impl; | ||
|
|
||
| import com.fasterxml.jackson.annotation.JsonTypeInfo; | ||
| import com.fasterxml.jackson.databind.BeanDescription; | ||
| import com.fasterxml.jackson.databind.DatabindContext; | ||
| import com.fasterxml.jackson.databind.JavaType; | ||
| import com.fasterxml.jackson.databind.MapperFeature; | ||
| import com.fasterxml.jackson.databind.cfg.MapperConfig; | ||
| import com.fasterxml.jackson.databind.jsontype.NamedType; | ||
| import java.util.Collection; | ||
| import java.util.HashMap; | ||
| import java.util.Map; | ||
| import java.util.TreeSet; | ||
| import java.util.concurrent.ConcurrentHashMap; | ||
|
|
||
| /** | ||
| * {@link com.fasterxml.jackson.databind.jsontype.TypeIdResolver} implementation | ||
| * that converts between (JSON) Strings and simple Java class names. | ||
| * | ||
| * @since 2.16 | ||
| */ | ||
| public class SimpleNameIdResolver | ||
| extends TypeIdResolverBase | ||
| { | ||
| protected final MapperConfig<?> _config; | ||
|
|
||
| /** | ||
| * Mappings from class name to type id, used for serialization. | ||
| *<p> | ||
| * Since lazily constructed will require synchronization (either internal | ||
| * by type, or external) | ||
| */ | ||
| protected final ConcurrentHashMap<String, String> _typeToId; | ||
|
|
||
| /** | ||
| * Mappings from type id to JavaType, used for deserialization. | ||
| *<p> | ||
| * Eagerly constructed, not modified, can use regular unsynchronized {@link Map}. | ||
| */ | ||
| protected final Map<String, JavaType> _idToType; | ||
|
|
||
| protected final boolean _caseInsensitive; | ||
|
|
||
| protected SimpleNameIdResolver(MapperConfig<?> config, JavaType baseType, | ||
| ConcurrentHashMap<String, String> typeToId, | ||
| HashMap<String, JavaType> idToType) | ||
| { | ||
| super(baseType, config.getTypeFactory()); | ||
| _config = config; | ||
| _typeToId = typeToId; | ||
| _idToType = idToType; | ||
| _caseInsensitive = config.isEnabled(MapperFeature.ACCEPT_CASE_INSENSITIVE_VALUES); | ||
| } | ||
|
|
||
| public static SimpleNameIdResolver construct(MapperConfig<?> config, JavaType baseType, | ||
| Collection<NamedType> subtypes, boolean forSer, boolean forDeser) | ||
| { | ||
| // sanity check | ||
| if (forSer == forDeser) throw new IllegalArgumentException(); | ||
|
|
||
| final ConcurrentHashMap<String, String> typeToId; | ||
| final HashMap<String, JavaType> idToType; | ||
|
|
||
| if (forSer) { | ||
| // Only need Class-to-id for serialization; but synchronized since may be | ||
| // lazily built (if adding type-id-mappings dynamically) | ||
| typeToId = new ConcurrentHashMap<>(); | ||
| idToType = null; | ||
| } else { | ||
| idToType = new HashMap<>(); | ||
| // 14-Apr-2016, tatu: Apparently needed for special case of `defaultImpl`; | ||
| // see [databind#1198] for details: but essentially we only need room | ||
| // for a single value. | ||
| typeToId = new ConcurrentHashMap<>(4); | ||
| } | ||
| final boolean caseInsensitive = config.isEnabled(MapperFeature.ACCEPT_CASE_INSENSITIVE_VALUES); | ||
|
|
||
| if (subtypes != null) { | ||
| for (NamedType t : subtypes) { | ||
| // no name? Need to figure out default; for now, let's just | ||
| // use non-qualified class name | ||
| Class<?> cls = t.getType(); | ||
| String id = t.hasName() ? t.getName() : _defaultTypeId(cls); | ||
| if (forSer) { | ||
| typeToId.put(cls.getName(), id); | ||
| } | ||
| if (forDeser) { | ||
| // [databind#1983]: for case-insensitive lookups must canonicalize: | ||
| if (caseInsensitive) { | ||
| id = id.toLowerCase(); | ||
| } | ||
| // One more problem; sometimes we have same name for multiple types; | ||
| // if so, use most specific | ||
| JavaType prev = idToType.get(id); // lgtm [java/dereferenced-value-may-be-null] | ||
| if (prev != null) { // Can only override if more specific | ||
| if (cls.isAssignableFrom(prev.getRawClass())) { // nope, more generic (or same) | ||
| continue; | ||
| } | ||
| } | ||
| idToType.put(id, config.constructType(cls)); | ||
| } | ||
| } | ||
| } | ||
| return new SimpleNameIdResolver(config, baseType, typeToId, idToType); | ||
| } | ||
|
|
||
| @Override | ||
| public JsonTypeInfo.Id getMechanism() { return JsonTypeInfo.Id.SIMPLE_NAME; } | ||
|
|
||
| @Override | ||
| public String idFromValue(Object value) { | ||
| return idFromClass(value.getClass()); | ||
| } | ||
|
|
||
| protected String idFromClass(Class<?> clazz) | ||
| { | ||
| if (clazz == null) { | ||
| return null; | ||
| } | ||
| // NOTE: although we may need to let `TypeModifier` change actual type to use | ||
| // for id, we can use original type as key for more efficient lookup: | ||
| final String key = clazz.getName(); | ||
| String name = _typeToId.get(key); | ||
|
|
||
| if (name == null) { | ||
| // 29-Nov-2019, tatu: As per test in `TestTypeModifierNameResolution` somehow | ||
| // we need to do this odd piece here which seems unnecessary but isn't. | ||
| Class<?> cls = _typeFactory.constructType(clazz).getRawClass(); | ||
| // 24-Feb-2011, tatu: As per [JACKSON-498], may need to dynamically look up name | ||
| // can either throw an exception, or use default name... | ||
| if (_config.isAnnotationProcessingEnabled()) { | ||
| BeanDescription beanDesc = _config.introspectClassAnnotations(cls); | ||
| name = _config.getAnnotationIntrospector().findTypeName(beanDesc.getClassInfo()); | ||
| } | ||
| if (name == null) { | ||
| // And if still not found, let's choose default? | ||
| name = _defaultTypeId(cls); | ||
| } | ||
| _typeToId.put(key, name); | ||
| } | ||
| return name; | ||
| } | ||
|
|
||
| @Override | ||
| public String idFromValueAndType(Object value, Class<?> type) { | ||
| // 18-Jan-2013, tatu: We may be called with null value occasionally | ||
| // it seems; nothing much we can figure out that way. | ||
| if (value == null) { | ||
| return idFromClass(type); | ||
| } | ||
| return idFromValue(value); | ||
| } | ||
|
|
||
| @Override | ||
| public JavaType typeFromId(DatabindContext context, String id) { | ||
| return _typeFromId(id); | ||
| } | ||
|
|
||
| protected JavaType _typeFromId(String id) { | ||
| // [databind#1983]: for case-insensitive lookups must canonicalize: | ||
| if (_caseInsensitive) { | ||
| id = id.toLowerCase(); | ||
| } | ||
| // Now: if no type is found, should we try to locate it by | ||
| // some other means? (specifically, if in same package as base type, | ||
| // could just try Class.forName) | ||
| // For now let's not add any such workarounds; can add if need be | ||
| return _idToType.get(id); | ||
| } | ||
|
|
||
| @Override | ||
| public String getDescForKnownTypeIds() { | ||
| // 05-May-2020, tatu: As per [databind#1919], only include ids for | ||
| // non-abstract types | ||
| final TreeSet<String> ids = new TreeSet<>(); | ||
| for (Map.Entry<String, JavaType> entry : _idToType.entrySet()) { | ||
| if (entry.getValue().isConcrete()) { | ||
| ids.add(entry.getKey()); | ||
| } | ||
| } | ||
| return ids.toString(); | ||
| } | ||
|
|
||
| @Override | ||
| public String toString() { | ||
| return String.format("[%s; id-to-type=%s]", getClass().getName(), _idToType); | ||
| } | ||
|
|
||
| /* | ||
| /********************************************************* | ||
| /* Helper methods | ||
| /********************************************************* | ||
| */ | ||
|
|
||
| /** | ||
| * If no name was explicitly given for a class, we will just | ||
| * use simple class name | ||
| */ | ||
| protected static String _defaultTypeId(Class<?> cls) | ||
| { | ||
| String n = cls.getName(); | ||
| int ix = Math.max(n.lastIndexOf('.'), n.lastIndexOf('$')); | ||
| return (ix < 0) ? n : n.substring(ix+1); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.