Skip to content

ObjectMapper serializes CharSequence subtypes as POJO instead of as String (JDK 15+) #3305

Closed
@stevenupton

Description

@stevenupton

Describe the bug
I have a class that implements CharSequence and in Java 14 and below the class was serialised correctly.

In Java 15 the JSON generated is

{"empty": false}

I believe the change was introduced in the CharSequence API by the introduction of the method isEmpty().

It appears the POJOPropertiesCollector._addGetterMethod collects the method isEmpty();

The class is then identified as a Bean type object, and uses a BeanSerializer to serialize the class. In Java 14 ToStringSerializer would be used to serialize the class.

Version information
Jackson 2.11.3

To Reproduce

See simple class to reproduce:

`
public class TestMapper
{

private final static ObjectMapper mapper;     

static
{
    mapper = new ObjectMapper();
    mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
 
}


private static class TestObj implements CharSequence, Serializable
{

    private String str;
    
    private TestObj(String str)
    {
        this.str = str;
    }
    
    @Override
    public int length()
    {
        return str == null ? 0 : str.length();
    }

    @Override
    public char charAt(int index)
    {
        return str == null ? 0 : str.charAt(index);
    }

    @Override
    public CharSequence subSequence(int start, int end)
    {
        return str == null ? null : str.subSequence(start, end);
    }

    @Override
    public String toString()
    {
        return str;
    }
    
}

public static void main(String[] args)
{
    TestObj obj = new TestObj("Hello World");
    StringWriter writer = new StringWriter();
    try
    {
        mapper.writeValue(writer, obj);
        System.out.println(writer.toString());
    }
    catch(Exception e)
    {
        //this should not throw
    }
}

}

`

Expected behaviour
Expected "Hello World"

Actual
{"empty": false}

Running in Java 14 or below the expected result is returned

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions