[SalesForce] SOQL query exclude null values in apex class

We have following values:


|Id  | Name  |Language|
|1   | abc   |        |

When I query the above record and debug this record in apex class it shows:-

(Library__c:{Id=xxxxxxxxxxxx, Name=abc})

It is not showing language field Why?

Actually, I need to create JSON from the query result. As the query result not showing the null or empty values, therefore, Json is also not including the null and empty values.

Best Answer

you can do the following:

list<Map<String, Object>> aa = new list<Map<String, Object>> ();
SObject[] b = [Select id, name, Language__c from Library__c];

for (SObject b : sobjects) {
    Map<String, Object> a = new Map<String, Object> ();
    for (SObjectField f : account.sobjecttype.getdescribe().fields.getmap().values()) {
        try { a.put(String.valueOf(f), b.get(f)); }
        catch(Exception e) { a.put(String.valueOf(f), null); }
    }
    aa.add(a);
}
System.debug(json.serialize(aa));

If you don't want all the non-query'd fields to be null values in your json you can adjust the list of Sobjectfield returned by the describe.

If it's just the language field you wan't to check you can do the following:

list<Map<String, Object>> aa = new list<Map<String, Object>> ();
SObject[] b = [Select id, name, Language__c from Library__c];

for (SObject b : sobjects) {
    Map<String, Object> a = new Map<String, Object> ();
    try { a.put('Language__c', b.get('Language__c')); }
    catch(Exception e) { a.put('Language__c', null); }
    aa.add(a);
}
System.debug(json.serialize(aa));
Related Topic