Skip to content

Delegating creator fails to work for binary data (byte[]) with binary formats (CBOR, Smile) #1711

@ghost

Description

Jackson Versions: 2.8.9, 2.9.0.pr4

This issue might belong to jackson-dataformats-binary.

I created a class which is basically a wrapper around a byte[], using @JsonValue and @JsonCreator.
This works fine using the default JsonFactory, however when using a SimleFactory or CBORFactory (and probably others) the deserialization fails: It returns a byte[] instead of the expected target class (which causes a ClassCastException in the calling code).

This problem only occurs with byte[]. Other types such as int[], String[] or byte[][] are fine.

public class TestByteArray {
    private static class ByteArray {
        private final byte[] val;

        @JsonCreator public ByteArray(byte[] val) { this.val = val;}

        @JsonValue public byte[] getValue() { return val;}
    }

    public static void main(String[] args) throws IOException {
        //This works fine
        test(new ObjectMapper(new JsonFactory()));
        //This throws java.lang.ClassCastException: [B cannot be cast to TestByteArray$ByteArray
        test(new ObjectMapper(new SmileFactory()));
        System.out.println("No exception thrown.");
    }

    private static void test(ObjectMapper mapper) throws IOException {
        byte[] bytes = {1, 2, 3, 4, 5};
        ByteArray read = mapper.readValue(mapper.writeValueAsBytes(new ByteArray(bytes)), ByteArray.class);
        if (!Arrays.equals(bytes, read.val))
            throw new IllegalStateException("Arrays not equal");
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions