I am looking for an elegant and unhacky way to handle deserialization of a JSON into an Apex type where some of the properties are known and some are not.

Assumption: At least for now the unknown properties are flat primitives. So no Maps or List or nested structures.

So this JSON

    age: 34,
    name: 'James',

    xyz: 2323,
    abc: '2131'

should be parsed by calling

Person p = JSON.deserialize(json, Person.class);

where Person.cls looks like this:

public class Person {
    public Integer age;
    public String name;

    public Map<String, Object> properties;


I know that this can be done in other languages, but I (until today) heard of no working solution in Apex.


I was toying around with some ideas for this and ended up documenting my work in this repo.

tl;dr: Here's the relevant Apex file and some usage examples.


This was the closest solution I could come up with and its good enough:

public class Person {

    public final String knownProperty;

    private Map<String, Object> unknownProperties = new Map<String, Object>();

    public Object get(String propertyName) {
        return unknownProperties.get(propertyName);

    public static Person newInstance(String jsonString) {
        Person result = (Person) JSON.deserialize(jsonString, Person.class);
        result.unknownProperties = (Map<String, Object>) JSON.deserializeUntyped(jsonString);
        return result;

    public static List<Person> newInstances(String jsonString) {
        List<Person> result = (List<Person>) JSON.deserialize(jsonString, List<Person>.class);

        Integer i = 0;

        for(Object properties : (List<Object>) JSON.deserializeUntyped(jsonString)) {
            Person person = result.get(i);
            person.properties = (Map<String, Object>) properties;

        return result;
  • 1
    Nifty! Can't think of another solution off hand – Brian Miller Jun 11 '20 at 14:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.