简体   繁体   English

为什么 Jackson 允许字节值超过 MAX_BYTE

[英]Why Jackson allows to Byte value more than MAX_BYTE

I'm receiving invalid value for Byte field during deserialization.我在反序列化期间收到无效的Byte字段值。

Json: Json:

{"byteField" : 128 }

Java: Java:

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

After deserialization I'm receiving Dto.byteField = -128反序列化后,我收到Dto.byteField = -128

I found next code in Jackon-core library v.2.11.0 in com.fasterxml.jackson.core.JsonParser#getByteValue我在com.fasterxml.jackson.core.JsonParser#getByteValue的 Jackon-core 库 v.2.11.0 中找到了下一个代码

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.但找不到问题 JACKSON-804 以及有关字节范围的任何讨论。

Question:问题:

  • Why Jackson allows to byte be more than 127?为什么 Jackson 允许字节超过 127?

Java doesn't allow unsigned bytes, but the unsigned binary representation of 128 is the same as the two's complement of -128 ; Java 不允许使用无符号字节,但是128的无符号二进制表示与-128的二进制补码相同; they're both 0b10000000 .他们都是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. Jackson 所做的是允许您决定该字段的语义:这可以是 8 位无符号字节,也可以是 8 位有符号字节。 It's counter-intuitive, and arguably incorrect, but that's pretty clearly the intent here.这是违反直觉的,并且可以说是不正确的,但这显然是这里的意图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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