5

I have a valid UUID in string format

7a041f81-1214-41e5-bb58-9a46b2ca08d4

but when I user a ObjectMapper to convert it to a UUID I keep getting this error.

    UUID uuid = mapper.readValue("7a041f81-1214-41e5-bb58-9a46b2ca08d4",UUID.class);

error:

com.fasterxml.jackson.core.JsonParseException: Unexpected character ('a' (code 97)): Expected space separating root-level values at [Source: (String)"7a041f81-1214-41e5-bb58-9a46b2ca08d4"; line: 1, column: 3] at com.xxxx.yyyyy.zzzzz.Test.callTest(BmcEventListenerTest.java:22

how can I convert the string to UUID and why do I keep getting this error?

Mahesh Waghmare
  • 726
  • 9
  • 27

1 Answers1

5

You don't need Object mapper, you can do the following

UUID obj = UUID.fromString("7a041f81-1214-41e5-bb58-9a46b2ca08d4"); 

Demo: https://onecompiler.com/java/3v2sr8pk8

karthikdivi
  • 3,466
  • 5
  • 27
  • 46
  • 1
    @Hummingbird because you are using classes that parse json without any json being involved – f1sh Sep 19 '19 at 13:03
  • @f1sh ok so i'm curious would this format work?? `"{"uuid":7a041f81-1214-41e5-bb58-9a46b2ca08d4}"` ?? –  Sep 19 '19 at 13:12
  • 2
    JSON doesn't have a UUID type - The JSON parser is seeing the leading '7' and assuming it can parse a number, then it encounters the 'a' and is forced to give up because it can't parse the string into a number anymore. – swpalmer Sep 19 '19 at 13:43
  • 1
    Your JSON needs to have quotes around the value part, so the UUID is initially read as a String. Without it being a string, it is invalid JSON, as it is not a number or boolean , etc. – swpalmer Sep 19 '19 at 13:46
  • If you have to use the mapper only then you can do the following ```mapper.readValue("\"7a041f81-1214-41e5-bb58-9a46b2ca08d4\"", UUID.class);``` Please do accept the anser, if it solved your problem. – karthikdivi Sep 19 '19 at 13:47