JSON解析为布尔值为TRUE或FALSE

JSON解析为布尔值为TRUE或FALSE

本文介绍了使用Jackson JSON解析为布尔值为TRUE或FALSE的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Jackson注释将JSON响应解析为POJO对象。我在POJO中使用布尔变量来映射来自JSON的值true和false。但突然之间,我们将JST的值变为TRUE和FALSE,并解析了这些值的失败。
任何人都可以建议将它映射到布尔值的方法,因为这个变量被用在很多地方,我不想将逻辑变为String到布尔值。

I am using Jackson annotation for parsing JSON response into POJO object.I was using boolean variable in POJO for mapping values "true" and "false" coming from JSON. But suddenly we are getting value as "TRUE" and "FALSE" into JSON and parsing failing for these values.Can anyone suggest way to map it to boolean as this variable is used so many places where i don't want to change logic to String to Boolean .

推荐答案

这不是一个真正的问题,这基本上是BeanUtils的工作方式。

It isn't really an issue, this is basically the way BeanUtils works.

对于布尔 vars,杰克逊删除了 setter name用于派生它在编组到JSON时期望变量名称的内容,并将 set 添加到相同的派生名称以解组回POJO。

For boolean vars, Jackson removes is from the setter name to derive what it expects the variable name to be when marshalling to JSON and adds set to that same derived name to unmarshal back to a POJO.

所以布尔值isFooTrue; 最终为 fooTrue 时编组为JSON,当解组它时会尝试调用 setIsFooTrue(); ,这是不正确的。

So boolean isFooTrue; ends up as fooTrue when marshalled to JSON, and when unmarshalling it would attempt to call setIsFooTrue();, which isn't the correct.

如果您正在使用IDE并且生成了getter / setter,您可能会注意到生成的 boolean的代码是forFoo; 基本上忽略 ,好像var名称只是 foo

If you're using an IDE and you generated your getter/setters, you'll probably notice that the generated code for boolean isFoo; basically ignores the is as if the var name was just foo:

private boolean isFoo;

public boolean isFoo() {
    return isFoo;
}

public void setFoo(boolean isFoo) {
    this.isFoo= isFoo;
}

两个选项是删除 ,或者将 添加到setter名称。

Two options are to remove the is from the var name, or add the is to the setter name.

这篇关于使用Jackson JSON解析为布尔值为TRUE或FALSE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 18:42