I can't find any method on the Boolean
class to serialize a Boolean to "1" and "0" instead of "true" and "false".
Is there any native function to开发者_StackOverflow do that ? If not, what is the best way (most optimized way) ?
Update: I indeed mean to produce a String
out of a Boolean
.
If you're talking about producing a String
from a given Boolean
, then no, there is no built-in method that produces "0" or "1", but you can easily write it:
public static String toNumeralString(final Boolean input) {
if (input == null) {
return "null";
} else {
return input.booleanValue() ? "1" : "0";
}
}
Depending on your use case, it might be more appropriate to let it throw a NullPointerException
if input
is null. If that's the case for you, then you can reduce the method to the second return
line alone.
You can use CompareTo:
public static Integer booleanToInteger(Boolean bool)
{
if(bool == null) return null;
else return bool.compareTo(Boolean.FALSE);
}
If you want to serialise to a char you can do
public static char toChar(final Boolean b) {
return b == null ? '?' : b ? '1' : '0';
}
I am not sure but just throwing it out. you can use your own Decorator class.
Use Thrift API:
TSerializer serializer = new TSerializer(new TSimpleJSONProtocol.Factory());
String json = serializer.toString(object);
It will boolean to 0 or 1 instead of true/false.
精彩评论