How to find the Data type of field in Apex ?
I had problem statement, where the currency field value need to be put into json along with the Currency sign. But since in the backend/Apex this value is stored as Decimal or Double, there is no direct way to identify it.
So I have put this below piece of code to find the Datatype that we see in the Object manager settings and with that we can do the formatting as an when required.
String type='CustomObjectName__c';
Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
Schema.SObjectType myobjectSchema = schemaMap.get(type);
Map<String, Schema.SObjectField> fieldMap = myobjectSchema.getDescribe().fields.getMap();
for (String fieldName: fieldMap.keySet()) {
//It provides to get the object fields label
String fieldLabel = fieldMap.get(fieldName).getDescribe().getLabel();
//It provides to get the object fields data type.
Schema.DisplayType fielddataType = fieldMap.get(fieldName).getDescribe().getType();
if(fielddataType != Schema.DisplayType.CURRENCY)
//Do your work here
if(fielddataType != Schema.DisplayType.TextArea)
//Do your work here
if(fielddataType != Schema.DisplayType.String)
//Do your work here
}
I hope this should have solved your problem.
There’s another solution for a problem if a person is looking for creation of json and in that json, you want to perform the action that is a bit different from the above solution, then you can take this approach:
public JSONGenerator updateJsonString(JSONGenerator gen, List<String> fields, SObject obj, String objectAPILabel)
{ //Get the map of the fields
Map<String, Schema.SObjectField> fieldMap = obj.getSObjectType().getDescribe().fields.getMap();
for(String field : fields){
//Retreiving the Display type of the field
Schema.DisplayType fieldDataType = fieldMap.get(field).getDescribe().getType();
if(obj.get(field) != null){
if(obj.get(field) instanceOf Date){
Date dt = Date.valueOf(obj.get(field));
gen.writeObjectField(objectAPILabel + '.' + field, dt.month() + '/'+ dt.day() + '/' + dt.year());
}
else if(Schema.DisplayType.CURRENCY == fieldDataType){
gen.writeObjectField(objectAPILabel + '.' + field, '$' + obj.get(field));
}
else {
gen.writeObjectField(objectAPILabel + '.' + field, obj.get(field));
}
} else {
gen.writeObjectField(objectAPILabel + '.' + field, '');
}
}
return gen;
}