Skip to main content

Here's a use-case I recently came across for generics. I am writing JSON deserializer classes for a REST API with multiple resources. Each resource also has a paginated response.

 

For example, it has a User response:

public class User {

public String id;

public String userName;

}

And a PaginatedUsers response:

public class PaginatedUsers {

public String nextPage;

public Integer pageNumber;

public User[] results;

}

Without generics, I need to write a deserializer for every paginated response for every resource (I can use inheritance to remove some of the boilerplate, but that actually increases my number of classes by one.) With generics, I could write a single paginated deserializer for all resources:

public class PaginatedResource<T> {

public String nextPage;

public Integer pageNumber;

public T[] results;

}

Then deserialize like this:

PaginatedResource<User> paginatedUserResponse = (PaginatedResource<User>)JSON.deserialize(

res.getBody(),

PaginatedResource<User>.class // <-- Will this be possible?

);

3 answers
  1. Aug 29, 2023, 12:59 PM

    @Andres Perez (ELTORO.it) In this example, User isn't an SObject. It's a User table from the external service. The idea is that the response would be deserialized and processed, so upcasting to Object wouldn't satisfy the use case either. Here's what the rest of the processing logic might look like

     

    PaginatedResource<ExternalResourceUser> paginatedUserResponse = (PaginatedResource<ExternalResourceUser>)JSON.deserialize(

    res.getBody(),

    PaginatedResource<ExternalResourceUser>.class

    );

    Contact[] contacts = new List<Contact>();

    for (ExternalResourceUser u : paginatedUserResponse.results) {

    contacts.add(

    // v--- The response body needs to be deserialized so that these attributes exist

    FirstName = u.givenName,

    LastName = u.surname,

    Email = u.emailAddress

    )

    }

0/9000