Add null check before encoding