Refs #2626: Better JSON serialization. Some refactoring and code cleanup.