Search code examples
javamongodbbson

Confusion with string.getBytes()


I have a byte array byteObj which is serialized by BSON.

String strObj = new String(byteObj)
System.out.println(byteObj.length)
System.out.println(strObj.getBytes().length)

The result is 152 and 154. And these two byte arrays are not the same. How can I recover the original bson byte array from the string?

update:

152 154
[-104, 0, 0, 0, 4, 116, 105, 116, 108, 101, 0, 80, 0, 0, 0, 2, 48, 0, 5, 0, 0, 0, 116, 104, 105, 115, 0, 2, 49, 0, 3, 0, 0, 0, 105, 115, 0, 2, 50, 0, 2, 0, 0, 0, 97, 0, 2, 51, 0, 5, 0, 0, 0, 116, 104, 105, 115, 0, 2, 52, 0, 2, 0, 0, 0, 97, 0, 2, 53, 0, 3, 0, 0, 0, 105, 115, 0, 2, 54, 0, 6, 0, 0, 0, 116, 105, 116, 108, 101, 0, 0, 4, 99, 111, 110, 116, 101, 110, 116, 0, 51, 0, 0, 0, 2, 48, 0, 5, 0, 0, 0, 116, 104, 105, 115, 0, 2, 49, 0, 2, 0, 0, 0, 97, 0, 2, 50, 0, 8, 0, 0, 0, 99, 111, 110, 116, 101, 110, 116, 0, 2, 51, 0, 3, 0, 0, 0, 105, 115, 0, 0, 0]
[-17, -65, -67, 0, 0, 0, 4, 116, 105, 116, 108, 101, 0, 80, 0, 0, 0, 2, 48, 0, 5, 0, 0, 0, 116, 104, 105, 115, 0, 2, 49, 0, 3, 0, 0, 0, 105, 115, 0, 2, 50, 0, 2, 0, 0, 0, 97, 0, 2, 51, 0, 5, 0, 0, 0, 116, 104, 105, 115, 0, 2, 52, 0, 2, 0, 0, 0, 97, 0, 2, 53, 0, 3, 0, 0, 0, 105, 115, 0, 2, 54, 0, 6, 0, 0, 0, 116, 105, 116, 108, 101, 0, 0, 4, 99, 111, 110, 116, 101, 110, 116, 0, 51, 0, 0, 0, 2, 48, 0, 5, 0, 0, 0, 116, 104, 105, 115, 0, 2, 49, 0, 2, 0, 0, 0, 97, 0, 2, 50, 0, 8, 0, 0, 0, 99, 111, 110, 116, 101, 110, 116, 0, 2, 51, 0, 3, 0, 0, 0, 105, 115, 0, 0, 0]

First is the BSON byte array.

update 2: the test code

    BSONObject ob = new BasicBSONObject()
            .append("title", Arrays.asList(new String[]{"this", "is", "a", "this", "a", "is", "title"}))
            .append("content", Arrays.asList(new String[]{"this", "a", "content", "is"}));


    byte[] ahaha = BSON.encode(ob);
    BSON.decode(ahaha);

    // BSON.decode(new String(ahaha).getBytes());

    byte[] strByte = new String(ahaha).getBytes();

    System.out.println(ahaha.length + "\t" + strByte.length);
    System.out.println(Arrays.toString(ahaha));
    System.out.println(Arrays.toString(strByte));

See How do you convert binary data to Strings and back in Java? for the solution of convert binary data to string and vice versa.


Solution

  • Reason for the difference is conversion of bytes to String. Note that the first byte is negative. Here is explanation from Javadoc:

    The length of the new String is a function of the charset, and hence may not be equal to the length of the byte array. The behavior of this constructor when the given bytes are not valid in the default charset is unspecified.

    The CharsetDecoder class should be used when more control over the decoding process is required.