简体   繁体   中英

Why Jackson allows to Byte value more than MAX_BYTE

I'm receiving invalid value for Byte field during deserialization.

Json:

{"byteField" : 128 }

Java:

class Dto {
     private Byte byteField;
     ... getter/setter
}

After deserialization I'm receiving Dto.byteField = -128

I found next code in Jackon-core library v.2.11.0 in com.fasterxml.jackson.core.JsonParser#getByteValue

public byte getByteValue() throws IOException {
    int value = getIntValue();
    // So far so good: but does it fit?
    // [JACKSON-804]: Let's actually allow range of [-128, 255], as those are uniquely mapped
    //  (instead of just signed range of [-128, 127])
    if (value < MIN_BYTE_I || value > MAX_BYTE_I) {
        throw new InputCoercionException(this,
                String.format("Numeric value (%s) out of range of Java byte", getText()),
                JsonToken.VALUE_NUMBER_INT, Byte.TYPE);
    }
    return (byte) value;
}

but not able to find issue JACKSON-804 as well as any discussion about byte range.

Question:

  • Why Jackson allows to byte be more than 127?

Java doesn't allow unsigned bytes, but the unsigned binary representation of 128 is the same as the two's complement of -128 ; they're both 0b10000000 .

What Jackson is doing is allowing you to decide the semantics of this field: This can either be an 8-bit unsigned byte, or it can be an 8-bit signed byte. It's counter-intuitive, and arguably incorrect, but that's pretty clearly the intent here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM