Enable toJSON function to return different types

Call `toJSON` first, if it returns a value other than object, it is properly serialized.