Hi all,
I'm trying to work with interfaces and related bean implementation of that interface. So far, all good.
I then tried to add some Map<String, Object> to the equation and I cannot understand why I get this result.
Short story: I'm trying to get the @class to be set to the interface name using a TypeIdResolver and it work as expected on a direct call but not when the object is inside a Map.
I simplified everything to get an example, here it is :
UserInterface.java
@JsonTypeInfo(use = Id.CLASS)
@JsonTypeIdResolver(UserTypeResolver.class)
public interface UserInterface
{
String getName();
}
UserImplementation.java
public class UserImplementation implements UserInterface
{
private String name;
@Override
public String getName()
{
return this.name;
}
public void setName(final String name)
{
this.name = name;
}
}
UserTypeResolver.java
public class UserTypeResolver implements TypeIdResolver
{
private JavaType baseType;
@Override
public void init(final JavaType baseType)
{
this.baseType = baseType;
}
@Override
public String idFromValue(final Object value)
{
return idFromValueAndType(value, value.getClass());
}
@Override
public String idFromValueAndType(final Object value, final Class<?> suggestedType)
{
return "com.example.jackson.UserInterface";
}
@Override
public String idFromBaseType()
{
return idFromValueAndType(null, this.baseType.getRawClass());
}
@Override
public JavaType typeFromId(final DatabindContext context, final String id)
throws IOException
{
return TypeFactory.defaultInstance().constructSpecializedType(this.baseType, UserImplementation.class);
}
@Override
public String getDescForKnownTypeIds()
{
return null;
}
@Override
public Id getMechanism()
{
return Id.CLASS;
}
}
And finally the test I played:
final UserImplementation user = new UserImplementation();
user.setName("test");
final Map<String, Object> parameters = new HashMap<>();
parameters.put("user", user);
final ObjectMapper mapper = new ObjectMapper();
mapper.enableDefaultTyping(DefaultTyping.JAVA_LANG_OBJECT, As.PROPERTY);
StringWriter writer = new StringWriter();
mapper.writeValue(writer, user);
System.out.println(writer);
writer = new StringWriter();
mapper.writeValue(writer, parameters);
System.out.println(writer);
The output is:
{"@class":"com.example.jackson.UserInterface","name":"test"}
{"user":{"@class":"com.example.jackson.UserImplementation","name":"test"}}
The expected output I'd like to see:
{"@class":"com.example.jackson.UserInterface","name":"test"}
{"user":{"@class":"com.example.jackson.UserInterface ","name":"test"}}
What am I doing wrong? Is that the expected output? What could I do to get the one I expect?
Thank you