Backport Message.to_json fix from 974f3619 to 2.8 branch

See 974f3619 and #190 for original fix. This is a
backport from 3.0.3 to 2.8.