1

I'm trying to retrieve a JSON object Via a remoteAction in Visualforce and I'm having some issues.

Controller:

    global without sharing class Article_Controller {

    @remoteAction
    global static JSONGenerator getQuickText() {

        JSONGenerator gen = JSON.createGenerator(true);
        List<Articles__c> lis = [SELECT Name,Message FROM Articles__c];
        gen.writeObject(lis);
        return gen;
    }
}

VF function

            $(document).ready(function() { 

                try {
                    Visualforce.remoting.Manager.invokeAction(
                        '{!$RemoteAction.Article_Controller .getQuickText}',
                        function(result, event) {
                            if (event.status) {
                                console.log(result);
                                var t = $.template('<div><img src="${Name}" />${Message}</div>');
                                 $(selector).append( t , {
                                 Name: jsonObj.Name,
                                 Message: jsonObj.Message
                                   });

                        }
                    }, {
                        escape: false
                    }
                    );
            } catch (ex) {
                alert(ex.message);
                console.log(ex);
                return false;
            }
        });

In the console I get the following error:

enter image description here

1
  • Can you try changing line return gen; to return gen.getAsString(); , also change the return type of the method from JSONGenerator to String?
    – javanoob
    Commented Feb 1, 2017 at 19:56

1 Answer 1

3

The simpler API to use for this situation is JSON.serialize:

global without sharing class Article_Controller {
    @RemoteAction
    global static String getQuickText() {
        return JSON.serialize([SELECT Name, Message FROM Articles__c]);
    }
}

The flexibility/complexity of JSONGenerator is rarely needed.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .