[SalesForce] JSON Deserialize Byte Array

I'm porting over a rest client from .NET to Apex and in the class that gets initiated by deserializing the JSON response, there is a byte[].

C# Example:

 public class MyResponse
  {
    public byte[] Image { get; set; }
  }

Wondering how to best handle this in apex? Maybe change it to a Blob or just a String type would work?

I likely don't really care about the data in the byte[], I just don't want it to break the Deserialization.

Best Answer

Assuming the system that is creating the JSON is using base64 encoding for the image, yes use Blob.

Here is an example of the deserialization/serialization working with base64 in Apex:

@isTest
private class ImageTest {
    private class MyResponse {
        Blob Image;
    }
    @isTest
    static void test() {
        // 2x2 PNG image
        String s = '{"Image":"iVBORw0KGgoAAAANSUhEUgAAAAIAAAACAgMAAAAP2OW3AAAADFBMVEWxf2/KgHhvwEfedoetG6yMAAAADElEQVQI12NoYCgAAAH0APFbzVilAAAAAElFTkSuQmCC"}';
        MyResponse b = (MyResponse) JSON.deserialize(s, MyResponse.class);
        String ss = JSON.serialize(b);
        System.assertEquals(s, ss);
    }
}
Related Topic