I am trying to create a JSON payload in a VF controller to send to middleware. I tried to use JSONGenerator.writeStringField(String, String) but kept getting error: "Can not write a field name, expecting a value"
I found the following question and answer, so I decided to give up on writeStringField and try JSON.serialize on inner classes instead.
Writing JSON using JSONGenerator with writeStringField()
Here is an example of the structure (XML) that I need to mimic/create:
<SalesPersons>
<SalesPerson>
<RecordType/>
<SalesPersonID>531</SalesPersonID>
<Status>A</Status>
</SalesPerson>
<SalesPerson>
<RecordType/>
<SalesPersonID>538</SalesPersonID>
<Status>A</Status>
</SalesPerson>
</SalesPersons>
Here are the classes I created:
public class SalesPersons{
List<SalesPerson> SalesPersons = new List<SalesPerson>();
public SalesPersons(){}
public void addSalesPerson(SalesPerson sp){
this.SalesPersons.add(sp);
}
}
public class SalesPerson{
String SalesPersonID;
String SalesPersonType;
String SubType;
String SalesPersonName;
public SalesPerson(User u){
SalesPersonID = u.EmployeeNumber;
SalesPersonType = 'S';
SubType = 'P';
SalesPersonName = u.Name;
}
}
Here is the JSON Payload that gets created from this:
{
"SalesPersons": [
{
"SubType": "P",
"SalesPersonType": "S",
"SalesPersonName": "SSO User",
"SalesPersonID": "101"
},
{
"SubType": "P",
"SalesPersonType": "S",
"SalesPersonName": "Admin User",
"SalesPersonID": null
}
]
}
Where I am stuck is on creating multiple arrays 'named' SalesPerson. The JSON that I am currently generating contains the info for multiple SalesPerson objects, but I need the String "SalesPerson" to be present in each.
Best Answer
A quick hack of the http://json2apex.herokuapp.com/ output produces:
Note that lists and arrays are interchangeable in this context.
To build the JSON: