Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

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 }
    ]
}]
share|improve this question
add comment

1 Answer

up vote 3 down vote accepted

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" } ]

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.