简体   繁体   中英

Base64 string representation of MongoDB ObjectId in Java?

Using the Java driver, what's the best way to convert an ObjectID to/from a string with Base64 encoding?

The ObjectIds will be part of a URL so I'd like to shorten them a bit.

The ObjectId class does have a toString() method, and a string may be provided in the constructor. However, these strings are base-16 (hexadecimal), and may bot be what you are looking for.

The API information may be found here: http://api.mongodb.org/java/current/

For base 64 encoding, a colleague of mine suggested that it may be preferable to use the toByteArray() method, and convert that to a base 64 string. Going the other way, the ObjectId constructor may be passed a byte array.

A Google search for "java library base64 encoding" reveals another Stack Overflow question that contains more detail on converting byte arrays to base 64 strings and back again.
Decode Base64 data in Java

The above thread contains a link to the base64 class, part of the Apache Commons Codec.
http://commons.apache.org/codec/apidocs/org/apache/commons/codec/binary/Base64.html

Hopefully this will get you where you need to go, or at least give you some additional options to consider.

I looked at the ObjectId source code and none of the internal string-ifying methods help.

Seems that you need to use ObjectId.toByteArray() and ObjectId( byte[]) in conjunction with an external Base64 encoder/decoder. The Java Mongo driver used to have com.mongodb.util.Base64 , but it doesn't seem to be part of the library any longer so I used the Base64 library in Apache Commons.

Here's an example of the conversions using Base64 in Apache Commons:

static public ObjectId toObjectId( String stringId)
{
    return new ObjectId( Base64.decodeBase64( stringId));
}

static public String toString( ObjectId objectId)
{
    return Base64.encodeBase64URLSafeString( objectId.toByteArray());
}

Use the javax.xml.bind.DatatypeConverter which is a part of Java

parseBase64Binary(String lexicalXSDBase64Binary) to convert a base64 into a binary string printHexBinary(byte[] val) to print it out as a hex string.

The advantage of this is you are not adding any additional libraries outside JavaEE5 or Java 6

您可以使用URLEncoderURLDecoder而不是Base64,它与MongoDB无关,但将字符串转换为有效的URL-Strings。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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