如果您正在为您的 Java 对象进行 JSON 序列化/反序列化。这是一个向您展示如何将 BitSet 转换为 base64 的示例。JSON 中的二进制存储在 base64 中。
import java.util.BitSet;
import java.util.Base64;
public class HelloWorld {
public static void main(String[] args) {
// Creating some examples of BitSet
BitSet first = new BitSet();
first.set(2); // 100
BitSet second = new BitSet();
second.set(4); // 10000
second.set(3); // 11000
BitSet third = new BitSet(2000);
third.set(5, 49);
// from Bitset to Base64
byte[] encoded = Base64.getEncoder().encode(first.toByteArray());
System.out.println("first="+first);
System.out.println("{'Chunk':'" +new String(encoded) + "'}");
encoded = Base64.getEncoder().encode(second.toByteArray());
System.out.println("second="+second);
System.out.println("{'Chunk':'" +new String(encoded) + "'}");
encoded = Base64.getEncoder().encode(third.toByteArray());
System.out.println("third="+third);
System.out.println("{'Chunk':'" +new String(encoded) + "'}");
// from Base64 to Bitset
byte[] decoded = Base64.getDecoder().decode("4P8H");
BitSet four = BitSet.valueOf(decoded);
System.out.println("four="+four);
decoded = Base64.getDecoder().decode(encoded);
BitSet thirdDecoded = BitSet.valueOf(decoded);
System.out.println("{'Chunk':'" +new String(encoded) + "'}");
System.out.println("third="+thirdDecoded);
}
}
输出 BitSet 为 base64
first={2}
{'successfulChunkMask':'BA=='}
second={3, 4}
{'successfulChunkMask':'GA=='}
third={5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48}
{'successfulChunkMask':'4P//////AQ=='}
输出 base64 到 BitSet
4P8H in base64
four={5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18}
{'successfulChunkMask':'4P//////AQ=='}
third={5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48}
如果您使用 NoSQL Java MapValue API(而不是对象的 JSON 表示),则需要从 byte[] 转换为 Bitset,反之亦然,并且不需要通过 base64。请参阅提供的代码中的 toByteArray() 和 BitSet.valueOf(byte[])。
如果您使用 NoSQL API 插入数据并提供 JSON 值,则解决方案是 base64 编码二进制字段 (java.util.BitSet)。如果您使用的是 SQL API,则相同