I am working on a REST Service that will desiralize the request body and interpret it. My understanding was that calling String.valueOf(objectInstance)
would just call objectInstance.toString()
. However, I am observing different behavior.
Working
Blob requestBody = Blob.valueOf('[{"key":"value"}]');
List<Object> body = (List<Object>)JSON.deserializeUntyped(requestBody.toString());
Not Working
Blob requestBody = Blob.valueOf('[{"key":"value"}]');
List<Object> body = (List<Object>)JSON.deserializeUntyped(String.valueOf(requestBody));
The above throws:
Line: 11, Column: 1
System.JSONException: Unexpected character ('B' (code 66)): expected a valid value (number, String, array, object, 'true', 'false' or 'null') at input location [1,2]
Best Answer
String.valueOf
returnsBlob[X]
for Blob values. I believe it does it this way becauseSystem.debug
internally usesString.valueOf
, and debugging a potentially non-Unicode stream into a Unicode String could break things. In other words, you can't reliably useString.valueOf
unless you can also use it inSystem.debug
and get the output you expect.String.valueOf
is always safe to use on a Blob, butBlob.toString
may result in an exception if the contents are not a Unicode String.Let's go with some examples to show how other standard and custom objects behave:
As you can see, you can never quite be sure what you're going to get out of it, unless you're using one of the concrete types listed in the documentation, which is currently: Date, DateTime, Decimal, Integer, and Long.
It does say that it supports "Object" generically, but generally speaking, you'll get the "debug safe" version of a string if you do so, which means it will probably be the wrong value.