[SalesForce] Parsing JSON Object with a value that may be either a string and array

Very new to Apex (first post here!)

I'm making an HTTP callout and receiving a JSON object formatted as such:

{"suggestions":{
"employees":
[{"first_name":"John","last_name":"Doe","specialty":["IT", "Development"]}],
"facilities":
[{"facility_name":""Facility A"}]}}

I used heroku to generate the following APEX class to handle to object:

public class MyClass {

public class Suggestions {
    public List<Employees> employees;
    public List<Facilities> facilities;
}


public class Facilities {
    public String facility_name;
}

public Suggestions suggestions;

public class Employees {
    public String first_name;
    public String last_name;
    public List<String> specialty;
}

I then used the following line in a method to do the parsing, where "json" is the JSON string returned from the callout:

(MyClass) System.JSON.deserialize(json, MyClass.class);

This works beautifulls when the "specialty" value returns a list of specialties. However, when a single String is returned (i.e., the employee only has one specialty), I am given a "Expecting List instead encountered…", which I'm assuming means it encountered a String instead of the expected List.

Is there a way to set up the class so that it can parse both data types? Or is there a way to check the data type of the value for "specialty" within .deserialize(), and insert some logic to change all Strings to Lists or vice versa?

Thanks for any help in advance!

Best Answer

You can try something like below

Map<String, Object> testMap = (Map<String, Object>) JSON.deserializeUntyped( jsonStr );

There is a detailed code example in the below url

https://www.salesforce.com/us/developer/docs/dbcom_apex290/Content/apex_System_Json_deserializeUntyped.htm