Why use JSON.serialize in @RemoteAction return statement

I can’t figure out why in an @RemoteAction method you would want to JSON.serialize the object being returned? I see this in a lot of code and I’m trying to understand the reasoning. I thought @RemoteAction automatically serialized it for you. In fact when doing this it appears you must decode using htmlDecode since it’s double encoded, once by Javascript Remoting and again by JSON.serialize method.

I trying to understand from an application design perspective the benefit of doing JSON.serialize and returning a String versus just returning the object/class when using JavaScript Remoteing.

Why do this:

public static List<User> searchUsersByName(String searchText) {
    return ChatterUIPeopleService.searchUsersByName(searchText);

Versus doing this:

public static String searchUsersByName(String searchText) {
    return JSON.serialize(ChatterUIPeopleService.searchUsersByName(searchText));


Since you’re not required to do this, I believe people just do it because they don’t know any better. They think “I’m calling this from Javascript, I better return JSON, so I need to serialize it.” It’s just one of many options that generate additional work, like returning String.valueOf(123) and sending it to a method that just does Integer.valueOf('123')

Source : Link , Question Author : Christian Anderson , Answer Author : Daniel N

Leave a Comment