Apex Cornor

Blob to String Conversion in Salesforce Apex:

Blob(b) cannot be converted to String directly using b.toString() or by using 'valueOf(b)' method. If it would have we might not get any error like this 'BLOB is not a valid UTF-8 string'. 
So what did we miss ? We missed this class.

Below is an example where a Json string stored in Static Resource is fetched in Apex code, here the body of Json is of type Blob. Inorder to get the String value of the Json body we are using a base64Encoding on the Blob value (sr.body as in below example) and again we are using base64Decoding to convert the Blob value to readable String value. Ask why? click here.

Example:

List<StaticResource> lst_src = [select Id,body from StaticResource where name like '%ExampleJson%'];

for(StaticResource sr :lst_src )
{
   string str = (sr.body).tostring()
   str = EncodingUtil.base64Decode(EncodingUtil.base64Encode(sr.body)).toString();
   System.debug('Json body: '+ str);
}

Popular posts from this blog

Salesforce Q&A Part 1:

Salesforce Q&A Part 2:

Salesforce Q&A Part 3: