Java – serialize “Boolean” as “1” and “0” instead of “true” and “false”

No method was found in the Boolean class to serialize Boolean values to '1' and '0' instead of 'true' and 'false'

Is there any local function? If not, what is the best way (the optimal way)?

Update: I do mean generating a Boolean string

Solution

If you are talking about generating a string from a given Boolean value, there is no built-in method to generate "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";
  }
}

According to your use case, if the input is null, it may be more suitable for throwing NullPointerException If this is the case, you can reduce the method to the second return line

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>