public
class
ConvertsObjectToJSON
{
public
static
string getJsonFromSObject(Id recordId)
{
String jsonData =
''
;
try
{
if
(String.isNotBlank(recordId))
{
String sObjectFields =
''
;
String objName = recordId.getSObjectType().getDescribe().getName();
Map<String, Schema.sObjectField> sObjectFieldMap = Schema.getGlobalDescribe().get(objName).getDescribe().fields.getMap();
Map<String, String> fieldMap =
new
Map<String, String>();
for
(Schema.SObjectField sfield: sObjectFieldMap.Values()){
Schema.DescribeFieldResult fieldDesc = sfield.getDescribe();
fieldMap.put(fieldDesc.getName(), fieldDesc.getType().name());
}
for
(String field: fieldMap.keySet()){
sObjectFields += field+
','
;
}
sObjectFields = sObjectFields.removeEnd(
','
);
String soqlQuery =
'SELECT '
+ sObjectFields +
' FROM '
+objName+
' WHERE Id =: recordId'
;
sObject sObj = Database.Query(soqlQuery);
JSONGenerator gen = JSON.createGenerator(
true
);
gen.writeStartArray();
gen.writeStartObject();
gen.writeFieldName(
'attributes'
);
gen.writeStartObject();
gen.writeStringField(
'type'
, objName);
gen.writeEndObject();
gen.writeFieldName(
'fields'
);
gen.writeStartObject();
for
(String field: fieldMap.keySet()){
if
(sObj.get(field) !=
null
){
gen.writeStringField(field, String.ValueOf(sObj.get(field)));
}
else
{
gen.writeStringField(field,
''
);
}
}
gen.writeEndObject();
gen.writeEndObject();
gen.writeEndArray();
jsonData = gen.getAsString();
}
}
catch
(Exception ex){
}
return
jsonData;
}
}