0

NOTE: The problem in this question is the cause of my previous question. I am generating UUID to bytes of length 16. Then adding it into JsonArray. When I get the first and the only element from JsonArray, .getString(0) and convert it back to bytes, the length of the resulted bytes is 24.

byte[] uuid = UUIDToolBox.fromUUIDToBytes(UUID.randomUUID());
System.out.println("uuid byteArray = " + Arrays.toString(uuid) + ", length:" + uuid.length );


JsonArray j = new JsonArray().add(uuid);
byte[] n = j.getString(0).getBytes(Charset.forName("UTF-8"));

System.out.println("from String = " + Arrays.toString(n) + ", length:" + n.length);


public static byte[] fromUUIDToBytes(UUID uuid) {
    ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
    bb.putLong(uuid.getMostSignificantBits());
    bb.putLong(uuid.getLeastSignificantBits());
    return bb.array();
}

I have tried many conversion charset types, but none worked.

Anum Sheraz
  • 2,383
  • 1
  • 29
  • 54
  • 1
    Use UUID.toString – Victor Gubin May 25 '18 at 10:17
  • I can directly convert it into String, but thats not what I want. I want the UUID to first convert it into byte[], so that I can add it into MySql column `id` of type binary(16). See my last question. https://stackoverflow.com/questions/50452958/cannot-add-uuid-of-type-binary-16-into-sql – Anum Sheraz May 25 '18 at 10:21
  • You cannot convert a random byte array to string with a character encoding like UTF-8. I think what you want is a string where each byte is represented as the hexadecimal value. So you should read this: https://stackoverflow.com/questions/9655181/how-to-convert-a-byte-array-to-a-hex-string-in-java – vanje May 25 '18 at 10:38
  • Why can't you just use the `toString()` of the UUID? The fact you need to store it in MySQL is not a good reason, proper conversion of the storage format needed in MySQL should be a concern for your DAO or ORM. – Mark Rotteveel May 25 '18 at 16:46

0 Answers0