简体   繁体   English

将 Boolean 序列化为“1”和“0”而不是“真”和“假”

[英]Serialize Boolean to “1” and “0” instead of “true” and “false”

I can't find any method on the Boolean class to serialize a Boolean to "1" and "0" instead of "true" and "false".我在 Boolean class 上找不到任何方法将Boolean序列化为“1”和“0”而不是“true”和“false”。

Is there any native function to do that?有没有本机 function 可以做到这一点? If not, what is the best way (most optimized way)?如果没有,最好的方法是什么(最优化的方法)?

Update: I indeed mean to produce a String out of a Boolean .更新:我确实是想从Boolean中产生一个String

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:如果您正在谈论从给定的Boolean生成String ,那么不,没有生成“0”或“1”的内置方法,但您可以轻松编写它:

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.根据您的用例,如果input为 null,则让它抛出NullPointerException可能更合适。 If that's the case for you, then you can reduce the method to the second return line alone.如果您是这种情况,那么您可以将该方法简化为单独的第二条return线。

You can use CompareTo :您可以使用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.您可以使用自己的装饰器 class。

Use Thrift API:使用节俭 API:

TSerializer serializer = new TSerializer(new TSimpleJSONProtocol.Factory());
String json = serializer.toString(object);

It will boolean to 0 or 1 instead of true/false.它将 boolean 为 0 或 1 而不是真/假。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM