Deserializing JSON with Reserved Words as Properties in Apex

Question
How to Deserialize JSON with Reserved Words as Property Names in Apex?
Is there a way to deserialize JSON into an Apex object using JSON.deserialize
, even if some of the property names in the JSON correspond to reserved keywords in Apex? For example, when deserializing JSON with reserved words, I want to deserialize a JSON string like this:
string jsonString = '{"currency" : "ABC"}';
public class JSONResult {
public string currency;
}
JSONResult res = (JSONResult) JSON.deserialize(jsonString, JSONResult.class);
system.debug(res);
However, when I try to do this, I encounter an error because the identifier name is a reserved word in Apex. How can I handle this scenario?
Answer
When deserializing JSON into Apex objects using JSON.deserialize
, you may encounter issues if the property names in the JSON are reserved words in Apex. For example, property names like class
, new
, object
, etc., are reserved keywords in Apex and cannot be directly used as field names in a class. This will result in errors when you try to deserialize the JSON data.
CRS Info Solutions provides excellent Salesforce training in New York, USA with hands-on projects and certification support. Their practical approach ensures you’re fully prepared for the job market..!
To handle this, you can use a technique to programmatically suffix the reserved words in the JSON before deserializing it. One way to do this is by writing a custom class that traverses the JSON data and appends a suffix (like _x
) to the reserved words, making them safe to use in Apex. Here’s an example of how this can be done:
Example Code:
public class DTO {
String toString_x;
String object_x;
String class_x;
String new_x;
}
String jsonString = '{"class": "ABC"}'; // This is the bad word (reserved word)
Object input = Json.deserializeUntyped(jsonString);
String suffixed = new ReservedWordSerializer(input).getAsString();
DTO dto = (DTO)Json.deserialize(suffixed, DTO.class);
System.debug(dto.class_x); // This will now work as 'class_x' is safe
In this solution, we use a custom ReservedWordSerializer
class that takes the JSON object, traverses it, and appends a suffix (_x
) to any key that is a reserved word. This makes the field names safe for deserialization into Apex classes.
See also: How to generate JSON for a APEX REST Post callout in Salesforce
ReservedWordSerializer
Class:
public class ReservedWordSerializer {
JsonGenerator g = Json.createGenerator(true); // true for pretty printing
public ReservedWordSerializer(Object obj) {
if (obj == null) {
g.writeNull();
} else if (obj instanceof Map<String,Object>) {
traverseMap((Map<String,Object>)obj);
} else if (obj instanceof List<Object>) {
traverseList((List<Object>)obj);
} else {
g.writeObject(obj);
}
}
public String getAsString() {
return g.getAsString();
}
void traverseMap(Map<String,Object> obj) {
List<String> keys = new List<String>(obj.keySet());
keys.sort();
g.writeStartObject();
for (String key : keys) {
Object value = obj.get(key);
g.writeFieldName(key + '_x'); // Appending '_x' to avoid reserved words
if (value == null) {
g.writeNull();
} else if (value instanceof Map<String,Object>) {
traverseMap((Map<String,Object>)value);
} else if (value instanceof List<Object>) {
traverseList((List<Object>)value);
} else {
g.writeObject(value);
}
}
g.writeEndObject();
}
void traverseList(List<Object> objs) {
g.writeStartArray();
for (Object obj : objs) {
if (obj == null) {
g.writeNull();
} else if (obj instanceof Map<String,Object>) {
traverseMap((Map<String,Object>)obj);
} else if (obj instanceof List<Object>) {
traverseList((List<Object>)obj);
} else {
g.writeObject(obj);
}
}
g.writeEndArray();
}
}
In this code, the ReservedWordSerializer
class uses a JsonGenerator
to serialize the data. It checks each field name and appends _x
to the field name if it is a reserved word. This approach ensures that the JSON can be deserialized into an Apex object, even if it contains reserved words.
By using this method, you can safely deserialize JSON data with reserved words and access those fields in your Apex class without encountering errors.
Boost Your Career with Salesforce Training in New York, USA
Our Salesforce training offers a thorough and immersive learning experience, equipping you with the essential skills to thrive in the CRM industry. The program covers key areas like Salesforce Admin, Developer, and AI, blending deep theoretical knowledge with practical, hands-on learning. By working on live projects and assignments, you’ll gain the expertise to tackle complex business challenges using Salesforce solutions. Our experienced instructors are dedicated to helping you build both technical skills and valuable industry insights.
Along with technical training, our Salesforce program in New York, USA, provides personalized mentorship, exam preparation, and interview coaching to help you stand out in the competitive job market. You’ll have access to extensive study materials, real-world project experience, and ongoing support throughout your learning path. Upon completing the course, you’ll be fully ready for certification exams and possess the practical skills and problem-solving abilities employers seek.
Don’t wait—join our free demo session today and take the first step toward a successful future! Register now for a free demo..!!