Find your content:

Search form

You are here

JSONGenerator writeString() Internal Error - Can not write text value, expecting field name

 
Share

I'm using the JSONGenerator writeString() method, and I'm receiving the following internal server error, "Can not write text value, expecting field name"? The debug logs indicate no errors, and neither does firebug. The documentation says that the writeString() method excepts a String and will write the specified string value (simple enough).

I've checked the known issues site; am I doing something wrong?

Class

public class ctrl_extjs_tree4_json {

    public String strJSON {get; private set;}

    public ctrl_extjs_tree4_json()
    {
        List<Account> accounts = [select id, name from Account Limit 3];
        this.strJSON = generateJSON(accounts); 
    }

    public String generateJSON(List<Account> accounts)
    {        
        JSONGenerator g = JSON.createGenerator(true); //boolean indicates pretty format
        g.writeStartArray();
        g.writeStartObject();
        g.writeString('test');
        g.writeEndObject();
        g.writeEndArray();

        return g.getAsString();
    }
}

Page

<apex:page controller="ctrl_extjs_tree4_json" contentType="text/javascript" showHeader="false" standardStylesheets="false" sidebar="false">
{!strJSON}
</apex:page>

I'm trying to ultimately produce a list of Accounts with sub list of Contacts (top 5), for an ExtJs tree panel. Something similar to the example below:

[{
    "success": true,
    "children": [
        { "id": 2, "name": "Phil", "leaf": true },
        { "id": 3, "name": "Nico", "expanded": true, "children": [
            { "id": 4, "name": "Mitchell", "leaf": true }
        ]},
        { "id": 5, "name": "Sue", "loaded": true }
    ]
}]

Attribution to: rcraven

Possible Suggestion/Solution #1

With JSON being essentially a key:value pair, it looks like you're attempting to assign a value to a missing attribute. Take a look at the writeFieldName method, to see how to define a JSON field.

Modifying the code to define a key, "Key" to assign the string 'Value' to, should do the trick.

JSONGenerator g = JSON.createGenerator(true); //boolean indicates pretty format

g.writeStartArray();
g.writeStartObject();
g.writeFieldName('Key'); // <-- Need to set this
g.writeString('Value');
g.writeEndObject();
g.writeEndArray();

system.debug(g.getAsString());

Will output the following:

21:57:54.101 (101039000)|USER_DEBUG|[9]|DEBUG|[ { "Key" : "Value" } ]


Attribution to: Mikey
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/5194

My Block Status

My Block Content