Spring @RequestParam 映射布尔值基于 1 或 0 而不是 true 或 false
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19178820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring @RequestParam mapping Boolean based on 1 or 0 instead of true or false
提问by Tommy
Why is Spring 3.2 only mapping my Boolean based on that the requestparam is "0" or "1" ?
为什么 Spring 3.2 仅根据 requestparam 为“0”或“1”来映射我的布尔值?
@RequestParam(required= false, defaultValue = "false") Boolean preview
Preview will only be "true"when the requestparam is "?preview=1"which is wierd
只有"true"当 requestparam"?preview=1"是奇怪的时候才会预览
I want it to be "?preview=true". How do I do that?
我想要它"?preview=true"。我怎么做?
回答by Tydaeus
I think we may need more detail in order to be effective answering your question.
我认为我们可能需要更多详细信息才能有效回答您的问题。
I have working Spring 3.2 code along the lines of:
我在以下方面使用 Spring 3.2 代码:
@RequestMapping(value = "/foo/{id}", method = RequestMethod.GET)
@ResponseBody
public Foo getFoo(
@PathVariable("id") String id,
@RequestParam(value="bar", required = false, defaultValue = "true")
boolean bar)
{
...
}
Spring correctly interprets ?bar=true, ?bar=1, or ?bar=yesas being true, and ?bar=false, ?bar=0, or ?bar=noas being false.
Spring 正确地将?bar=true、?bar=1、 或解释?bar=yes为真,而?bar=false、?bar=0、 或?bar=no为假。
True/false and yes/no values ignore case.
真/假和是/否值忽略大小写。
回答by Pavel Horal
Spring should be able to interpret true, 1, yesand onas trueboolean value... check StringToBooleanConverter.
Spring 应该能够将true、1、yes和on 解释为true布尔值......检查StringToBooleanConverter。
回答by Apex ND
you can use Hymanson's JsonDeserialize annotation, short and clean
你可以使用Hymanson的JsonDeserialize注解,简洁明了
create the following deserializer:
创建以下解串器:
public class BooleanDeserializer extends JsonDeserializer<Boolean> {
public BooleanDeserializer() {
}
public Boolean deserialize(JsonParser parser, DeserializationContext context) throws IOException {
return !"0".equals(parser.getText());
}
}
and add the annotation to your DTO like so:
并将注释添加到您的 DTO 中,如下所示:
public class MyDTO {
@NotNull
@JsonDeserialize(using = BooleanDeserializer.class)
private Boolean confirmation;
}

