I have to populate the values in a JSON structure. The values are obtained from the fields of a parent object and also the child object. I may have more than 1 child records of a parent object. how can I populate that in the below code. How can I traverse through all the child and update it in the JSON strcuture
String JSONString=JSON.serialize(
new Map<String, Object> {
'ElementA' => new Object[] {
new Map<String, Object> {
'ParentField1' => field1__C,
'ParentField2' => field2__C,
'child' => new Object[] {
new Map<String, Object> {
'childName' => how do i get each child Name to repeat here,
'childfield1' => how do i get each child's field 1 to repeat here
}
},
'ParentField3' => field3__C,
'ParentField4' => 'field4__C
}
}
);
Exact JSON:
{
"Parent": [{
"SerialNumber": "33455724",
"EventDay": "1",
"EventMonth": "12",
"EventYear": "2016",
"Child": [{
"Child": " ",
"Level1": " ",
"Level2": " ",
"Description": " ",
"RecordType": " "
}],
"AccountName": "Account 001",
"AccountNumber": "123333",
"Address": "NY",
"Contact": [{
"FirstName": " ",
"LastName": " ",
"Phone": " ",
"Address": " ",
"Email": " "
}],
"Lot": " ",
"Num": " "
}]
}
JSON2APex Class:
public class Child {
public String Child;
public String Level1;
public String Level2;
public String Description;
public String RecordType;
}
public class Parent {
public String SerialNumber;
public String EventDay;
public String EventMonth;
public String EventYear;
public List<child> Child;
public String AccountName;
public String AccountNumber;
public String Address;
public List<Contact> Contact;
public String Lot;
public String Num;
}
public class Contact {
public String FirstName;
public String LastName;
public String Phone;
public String Address;
public String Email;
}
public class JSON2Apex {
public List<parent> parent;
}
What I intend to do:
Parent__C pr = [select id,......... where id=parent.id];
Parent p = new Parent();
p.SerialNumber = pr.serial__c;
..
..
List<Child__C> c = [select childname,Level1,Level2,Description from child__c where child.parent__c = pr.id];
List<Child> ch = new List<Child>();
For(Child__c chld : c){
ch.Level1 = chld.Level1;
..
ch.RecordType = chld.RecordType;
}
p.Child = ch;
// similarly I will get the list of contact and do
p.Contact = contactList
List<parent> plist = new List<parent>();
plist.add(p);
JSON2Apex j = new JSON2Apex();
j.parent = plist
String JsonString = JSON.serialize(j);
Does the above code looks correct?
"SingularKeyName": [...]
. If yourvalue
is an array, thekey
name should be plural. So"children"
is more appropriate than"child"
, and"contacts"
is more appropriate than"contact"
, etc.