Parsing JSON in apex – getting error System.StringException: Unrecognized base64 character: {

apexbase64files

I am trying to parse a json i get from external system to salesforce using wrapper class.
The class works fine but for test class i am trying to hard code a string to test the class.

Below is the code, I have simplified the json for easier understanding.

String yourFilesContent = '{"MessageHeader":{"Version":"2.0"}}';
String base64Content = ( String ) JSON.deserialize( yourFilesContent, String.class );
Blob body = EncodingUtil.base64Decode(base64Content);

External system writes to file and i read from it and create data in salesforce objects.

When i run this code in developer console i keep getting the error as shown below

Line: 5, Column: 1 System.StringException: Unrecognized base64
character: {

How do i resolve this issue? Any help would be appreciated

Best Answer

Your simplification of the JSON here is detrimental, and is obscuring the issue. For purposes of providing an answer, I'll assume that there is some Base64 encoded string somewhere inside of the JSON you're actually receiving.

The primary issue I see is that you're trying to deserialize a JSON string into another String. This makes little sense. Your JSON here is not a single string, it's an object.

String base64Content = ( String ) JSON.deserialize( yourFilesContent, String.class ); looks very wrong to me. When I try to run this as anonymous apex, I get that the result is simply the first character in the JSON string, the {. As that's not used as a symbol in the Base64 character set, it's no wonder you're getting an error.

You should be deserializing to a custom Apex class that you've created (which mimics the structure of the JSON), or deserializing untyped into a Map<String, Object>. At the end of the day, you need to deserialize first, then pull out the Base64 encoded component, then decode it.

e.g.

String myJSON = '{"MessageHeader":{"Version":"2.0"}, "Content":{"B64Data":"IamBasE64="}}';

Map<String, Object> result = (Map<String, Object>)JSON.deserializeUntyped(myJSON);

Map<String, Object> content = (Map<String, Object>)result.get('Content');
String b64 = (String)content.get('B64Data');

System.debug(EncodingUtil.Base64Decode(b64));
Related Topic