… or at least pass in a specific class? Here is what I have right now:
private static invoice_response GetResponse(String jsonResponse) { invoice_response deserialized = (invoice_response) JSON.deserialize(jsonResponse, invoice_response.class); return deserialized; }
Since I have to deserialized a bunch of things… I’d like to have the following with Generics or perhaps another way:
private static invoice_response GetResponse<T>(String jsonResponse) { T deserialized = (T) JSON.deserialize(jsonResponse, T.class); return deserialized; }
Is this possible using Apex?
P.S. @MarkPond provided a solid attempt at the solution to this problem, but, alas, Apex only supports built in generics, thus I can’t properly “genericize” this method.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You could pass in the name of the type that can be used by the deserializer but unless these are sObjects you’re going to be stuck on making the return generic and strongly typed.
private static List<sObject> GetResponse(String jsonResponse, String jsonType) { // get the type for deserialization Type dataType = Type.forName(jsonType); // deserialize into a generic sObject list return type List<sObject> deserialized = (List<sObject>)JSON.deserialize(jsonResponse, dataType); return deserialized; }
It would be called like this:
List<sObject> objectsList = GetResponse('[{"name":"acme"}]', 'List<Account>'); List<Account> accountList = (List<Account>)GetResponse('[{"name":"acme"}]', 'List<Account>');
I would probably suggest using JSON.deserializeUntyped instead, though it becomes a bit less useful to have the helper method in this form.
private static Map<String, Object> GetResponse(String jsonResponse) { return (Map<String, Object>)JSON.deserializeUntyped(jsonResponse); }
If you want to see a solid example of using this mechanism and how you might build your classes to help work with a concrete type, take a look at this answer:
Write a generic JSON-serializable Parameters class…
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0