简体   繁体   English

杰克逊:有没有办法忽略布尔反序列化的0/1?

[英]Jackson: Is there a way to ignore 0/1 on Boolean deserialization?

I have a JSON object with a Boolean property that needs to allow only true or false during the deserialization. 我有一个带有Boolean属性的JSON对象,在反序列化期间只需要允许truefalse

Any value different of true and false should throw an exception. 任何不同的truefalse值都应该抛出异常。

How can I do that? 我怎样才能做到这一点?


eg: 例如:

Valid json: 有效的json:

{
  "id":1,
  "isValid":true
}

Invalid json: 无效的json:

{
  "id":1,
  "isValid":1
}

You need to disable ALLOW_COERCION_OF_SCALARS feature: 您需要禁用ALLOW_COERCION_OF_SCALARS功能:

import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        File jsonFile = new File("./resource/test.json").getAbsoluteFile();

        ObjectMapper mapper = new ObjectMapper();
        mapper.disable(MapperFeature.ALLOW_COERCION_OF_SCALARS);

        System.out.println(mapper.readValue(jsonFile, Pojo.class));
    }
}

class Pojo {

    private int id;
    private Boolean isValid;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public Boolean getIsValid() {
        return isValid;
    }

    public void setIsValid(Boolean valid) {
        isValid = valid;
    }

    @Override
    public String toString() {
        return "Pojo{" +
                "id=" + id +
                ", isValid=" + isValid +
                '}';
    }
}

Above code prints: 上面的代码打印:

Exception in thread "main" com.fasterxml.jackson.databind.exc.MismatchedInputException : Cannot coerce Number (1) for type java.lang.Boolean (enable MapperFeature.ALLOW_COERCION_OF_SCALARS to allow) at [Source: (File); 线程“main”中的异常com.fasterxml.jackson.databind.exc.MismatchedInputException :无法在[Source:(File);强制类型java.lang.Boolean (允许MapperFeature.ALLOW_COERCION_OF_SCALARS允许)强制Number(1); line: 3, column: 14] (through reference chain: Pojo["isValid"]) at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:63) line:3,column:14](通过引用链:Pojo [“isValid”])at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:63)

Well, it's not a for-any-case implementation, but may be it'll be suitable for you: 嗯,这不是一个任何案例的实现,但它可能适合你:

public class TestBooleanDeserializer extends JsonDeserializer<Boolean> {

  @Override
  public Boolean deserialize(JsonParser jsonParser, DeserializationContext context)
      throws IOException, JsonProcessingException {
    String str = jsonParser.getText();    
    boolean val = Boolean.valueOf(str);
    if (!val && Objects.nonNull(str) && !Objects.equals("false", str.toLowerCase())) {
      throw new RuntimeException("invalid JSON");
    }
    return val;
  }

}

Since a Boolean.valueOf is a result of check of the java.lang.Boolean# 由于Boolean.valueOf是检查java.lang.Boolean#的结果java.lang.Boolean#

public static boolean parseBoolean(String s) {
    return ((s != null) && s.equalsIgnoreCase("true"));
}

here: boolean val = Boolean.valueOf(str); 这里: boolean val = Boolean.valueOf(str); you'll check is it a true value or not. 你会检查它是否是true价值。 If not, you should check is it null or false : if (!val && Objects.nonNull(str) && !Objects.equals("false", str.toLowerCase())) if it's not you can throw an exception whatever you need. 如果没有,你应该检查是null还是falseif (!val && Objects.nonNull(str) && !Objects.equals("false", str.toLowerCase()))如果不是你可以抛出异常,无论你是什么需要。 Otherwise you'll return a boolean value 否则你将返回一个布尔值

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

相关问题 使用Jackson进行序列化和反序列化:如何以编程方式忽略字段? - Serialization and Deserialization with Jackson: how to programmatically ignore fields? 如果 Boolean 为空/假,如何告诉 Jackson 忽略它? - How to tell Jackson to ignore a Boolean if it is null/false? 有什么方法可以防止杰克逊场反序列化吗? - Is there any way to prevent field from deserialization in jackson? 如何在 jackson 反序列化期间忽略 json 数组的类型信息? - How to ignore type information on json arrays during jackson deserialization? 如果数据和 model 字段不是同一类型,则忽略 jackson 反序列化 - Ignore jackson deserialization if the data and model field are not of the same type 忽略Jackson反序列化中的中间数组包装对象 - Ignore intermediate array-wrapping objects in Jackson deserialization 忽略杰克逊反序列化的某些字段而无需更改模型 - Ignore some fields deserialization with jackson without changing model 使用类型信息优雅地忽略Jackson JSON反序列化中的未知类? - Gracefully ignore unknown class in Jackson JSON deserialization with type info? 杰克逊反序列化忽略属性不适用于@JsonView - Jackson deserialization ignore properties does not work properly with @JsonView 如何在没有杰克逊注释的情况下忽略某些字段进行反序列化? - How to ignore certain fields for deserialization without jackson annotations?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM