function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Anudeep BAnudeep B 

JSON.writeObject(); elaboration need

Ihave this JSON :  

public  class Exinteg {
public string result{get;set;}
public Exinteg()
{
    
    JSONGenerator jg = JSON.CreateGenerator(true);
    jg.writestartObject();
    jg.writestringfield('Name','Sathish');
    jg.writeNumberField('age',30);
    jg.writeFieldName('Account');
    list<account> acc= [select name,industry from account limit 2];  
    jg.writeObject(acc);
  // What processing internally at this line 
    jg.writeFieldName('myarray');
    jg.writestartArray();
    jg.writenumber(10);
    jg.writenumber(20);
    jg.writeEndArray();
    jg.writeEndObject();
    result=jg.getAsString();
    
}
}



{ "Name" : "Sathish", "age" : 30, "Account" : [ { "attributes" : { "type" : "Account", "url" : "/services/data/v33.0/sobjects/Account/0019000001Epo6BAAR" }, "Name" : "Sunkeert", "Id" : "0019000001Epo6BAAR", "Industry" : "Chemical" }, { "attributes" : { "type" : "Account", "url" : "/services/data/v33.0/sobjects/Account/0019000001Epo6CAAR" }, "Name" : "Samba", "Id" : "0019000001Epo6CAAR", "Industry" : "Chemical" } ], "myarray" : [ 10, 20 ] }



i was fetching only name and industry fields from account but why the other coming to JSON? which i didn't use in SOQL Query (in bold above).
Best Answer chosen by Anudeep B
kaustav goswamikaustav goswami
This is happening because you are writing the list of accounts retrieved to the JSON as a list of SObject. If you want to remove these then you will have iterate over the Account records and add them specifically to the JSON. Something like this - 
 
jg.writestartArray();
for(Account a : acc){
     jg.writestringfield('Name',a.Name);
     jg.writestringfield('Industry',a.Industry);
}
​jg.writeEndArray();

Thanks,
Kaustav

All Answers

kaustav goswamikaustav goswami
This is happening because you are writing the list of accounts retrieved to the JSON as a list of SObject. If you want to remove these then you will have iterate over the Account records and add them specifically to the JSON. Something like this - 
 
jg.writestartArray();
for(Account a : acc){
     jg.writestringfield('Name',a.Name);
     jg.writestringfield('Industry',a.Industry);
}
​jg.writeEndArray();

Thanks,
Kaustav
This was selected as the best answer
Anudeep BAnudeep B
That means in my above case     list<account> acc= [select name,industry from account limit 2]; this query will also fetch id, url those things even if i didn't mension? right?

to get only Name and Industry i need to use your code  am i correct?
kaustav goswamikaustav goswami
Yes you are correct.