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 .
问题:
回答1:
It isn't really an issue, this is basically the way BeanUtils works.
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.
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.
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;
}
Two options are to remove the is
from the var name, or add the is
to the setter name.
回答2:
I am not sure this is what you want. But it works.
Boolean param = Boolean.parseBoolean((String)yourValue);
The tested code is
public class program10 {
public static void main(String args[]) {
String yourValue = "TRUE"; // This is what you get from json.
Boolean param = Boolean.parseBoolean((String)yourValue);
if(param == true)
System.out.println("Value is true");
else
System.out.println("Value is false");
System.out.println(param);
}
}
回答3:
I also faced a similiar issue using Jackson Parser 1.8.5. Java POJO to JSON worked but same JSON back to Java POJO did not. In Java POJO, if a boolean variable is declared as
private Boolean isMyVar;
then the Jackson produces equivalent JSON as
{..,
"myVar" : false,
..
}
(I know the boolean variable naming is wrong here, but the JAR is third party and say you cannot change it!)
I think this is an issue with the way Jackson parser is designed to handle boolean values. I changed the JSON from "myVar" : false to "isMyVar" : false and it worked ok to create back the Java POJO from the JSON.
Anybody knows if this is still a bug or has it been resolved?