3

I would like to create JSON as a output, for that I have written one sample code, but in that code on line no 30 I am getting error as, 'System.JSONException: Can not start an object, expecting field name' can anyone please provide me the way to minimize that error

    public class JSonGeneratorDemo {

    public class Employee{
        String val = '';
        public Employee(){
           // this.val = val;
        }
    }    
    public static void generateJSONContent(){

        JSONGenerator gen = JSON.createGenerator(true);
        List<Integer> intList = new List<Integer>();
            intList.add(101);
            intList.add(201);
            intList.add(301);

        Employee test = new Employee();

        gen.writeStartObject();
        gen.writeStringField('Orgnization', 'Prorigo Software Pvt. Ltd.');
        gen.writeStringField('EmpName', 'Amol Jadhav');
        gen.writeNumberField('EmpId', 10);
        gen.writeStartObject();
        gen.writeObjectField('Remaining Employee Ids', intList);
        gen.writeEndObject();
        gen.writeFieldName('Demo Field');
        gen.writeObject(test);
        gen.writeEndObject();

        String pretty = gen.getAsString(); // Error on this line
        //System.debug('The Generated JSON :' +pretty);


    }
}
1
  • 2
    Much easier to serialize a class if you can. Should be few use cases where you need to use a generator.
    – Eric
    Jul 3, 2017 at 7:23

1 Answer 1

6

you need to specify name of field before creating object as value. if you want to have an array as value for Remaining Employee Ids field, you don't need to create object for it.

    gen.writeStartObject();
    gen.writeStringField('Orgnization', 'Prorigo Software Pvt. Ltd.');
    gen.writeStringField('EmpName', 'Amol Jadhav');
    gen.writeNumberField('EmpId', 10);
    gen.writeFieldName('Remaining Employee Ids');
    gen.writeObject(intList);
    gen.writeFieldName('Demo Field');
    gen.writeObject(test);
    gen.writeEndObject();

results in

{
    "Orgnization" : "Prorigo Software Pvt. Ltd.",
    "EmpName" : "Amol Jadhav",
    "EmpId" : 10,
    "Remaining Employee Ids" : [ 101, 201, 301 ],
    "Demo Field" : {
        "attributes" : {
            "type" : "Employee"
        }
    }
}
2
  • Thank you so much @Alexander it has worked for me. thanks again for your time and help Jul 3, 2017 at 7:10
  • @OleksandrBerehovskyi Unless I am missing something, you are using character constants for your strings. I am surprised that that would compile. Maybe consider replacing ' with " for your JsonGenerator fields. Good Jackson tip though! Appreciated. Nov 11, 2019 at 8:50

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.