Matthieu Napoli
Matthieu Napoli

Reputation: 49693

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".

Is there any native function to do that ? If not, what is the best way (most optimized way) ?

Update: I indeed mean to produce a String out of a Boolean.

Upvotes: 11

Views: 38909

Answers (5)

dereck
dereck

Reputation: 529

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.

Upvotes: -2

Eng.Fouad
Eng.Fouad

Reputation: 117665

You can use CompareTo:

public static Integer booleanToInteger(Boolean bool)
{
    if(bool == null) return null;
    else return bool.compareTo(Boolean.FALSE);
}

Upvotes: 4

Peter Lawrey
Peter Lawrey

Reputation: 533820

If you want to serialise to a char you can do

public static char toChar(final Boolean b) {
    return b == null ? '?' : b ? '1' : '0';
}

Upvotes: 2

Talha Ahmed Khan
Talha Ahmed Khan

Reputation: 15473

I am not sure but just throwing it out. you can use your own Decorator class.

Upvotes: -1

Joachim Sauer
Joachim Sauer

Reputation: 308239

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.

Upvotes: 13

Related Questions