2

I'm trying to generate:

"[{"hello" : "world"}]"

gen.writeStartObject();
gen.writeArrayStart();
gen.writeStartObject();
gen.writeStringFeild('hello', 'world');
gen.writeEndObject();
gen.writeArrayEnd();
gen.writeEndObject();

Throws the error: System.JSONException: Can not start an array, expecting field name

But the array in my example does not have a field name?

5

Right now, you open an object before opening your array. An object must consist of field value pairs. Here is an annotated version of what you wrote above, with your three typos corrected.

gen.writeStartObject();
// output: {
// remove this line

gen.writeStartArray();
// output: [
// your post had a typo here which I have fixed
// using writeStartArray rather than writeArrayStart

gen.writeStartObject();
// output: {

gen.writeStringField('hello', 'world');
// output: "hello": "world"
// your post had a typo here which I have fixed
// using writeStringField rather than writeStringFeild

gen.writeEndObject();
// output: }

gen.writeEndArray();
// output: ]
// your post had a typo here which I have fixed
// using writeEndArray rather than writeArrayEnd

gen.writeEndObject();
// output: }
// remove this line

Please note that JSONGenerator is almost never the correct choice for the job. It is almost universally simpler, easier to read, and better performance to just use out of the box serialization/deserialization. For example, here you could write just one line:

String payload = JSON.serialize(new List<Object> {
    new Map<String, String> { 'hello' => 'world' }
});
| improve this answer | |
  • 1
    Also its writeStartArray and writeEndArray – salesforce-sas Jul 29 '19 at 17:00
  • Thank you Adrian! – muchavie Jul 29 '19 at 17:35
  • 1
    @muchavie If this answer addressed your problem, please consider accepting it by clicking on the check mark/tick to the left of the answer, turning it green. This marks the question as resolved to your satisfaction, and awards reputation both to you and the person who answered. If you have >= 15 reputation points, you may also upvote the answer if you wish. There is no obligation to do either. – Adrian Larson Jul 29 '19 at 17:38
  • I already upvoted it. I don't know why it didn't turn green. – muchavie Jul 31 '19 at 13:53
  • Upvoting and accepting are completely different mechanisms. You have to click the little checkmark next to the answer to indicate that it has solved your problem. – Adrian Larson Jul 31 '19 at 13:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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