2017-09-22 124 views
1

我有一個項目需要嚴格的json策略。如何在jackson 2.9.x中禁用將0/1轉換爲true/false

例子:

public class Foo { 
    private boolean test; 

    ... setters/getters ... 
} 

繼JSON應該工作:

{ 
    test: true 
} 

而且下面應該會失敗(拋出異常):

{ 
    test: 1 
} 

同樣爲:

{ 
    test: "1" 
} 

基本上我想反序列化失敗,如果有人提供的東西不是truefalse。不幸的是傑克遜將1視爲true,0視爲false。我無法找到禁用這種奇怪行爲的反序列化功能。

回答

1

可以禁止docs

功能,確定從次級 表示強制轉換是否允許進行簡單的非文本標量類型MapperFeature.ALLOW_COERCION_OF_SCALARS : 數字和布爾值。

如果你還希望它爲null工作,使DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVESMore Info

ObjectMapper mapper = new ObjectMapper(); 

//prevent any type as boolean 
mapper.disable(MapperFeature.ALLOW_COERCION_OF_SCALARS); 

// prevent null as false 
// mapper.enable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES); 

System.out.println(mapper.readValue("{\"test\": true}", Foo.class)); 
System.out.println(mapper.readValue("{\"test\": 1}", Foo.class)); 

結果:

Foo{test=true} 

Exception in thread "main" 
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot 
coerce Number (1) for type `boolean` (enable 
`MapperFeature.ALLOW_COERCION_OF_SCALARS` to allow) at [Source: 
(String)"{"test": 1}"; line: 1, column: 10] (through reference chain: 
Main2$Foo["test"]) 
+0

謝謝,這是我需要的。 –

相關問題