[SalesForce] Deserialize JSON to SObject

Following code is giving me common.apex.runtime.impl.ExecutionException

String jsonText = '{"Data": {"attributes": {"type": "Contact"},"Id": "0036100000JUXKkAAP","Description": "","LastName": "Testing"}}';
Map<String, Object> cObjMap = (Map<String, Object>) JSON.deserializeUntyped(jsonText); String cObjJson = JSON.serialize(cObjMap.get('Data')); SObject customObject = (SObject)JSON.deserialize(cObjJson, SObject.class);

The problem is in fact that Map<String,Object> gets re-ordered during serialize/deserialize and "attributes" node is moved to last position.

That causes deserialize to SObject to fail as it requires "attributes" to be in first position, just like in jsonText example.

I know that defining separate class that would map all key/value pairs from JSON and deserializing to it would work, but I don't have exact structure as keys might vary.

Do you have any idea how to accomplish this?

Thank You!

Best Answer

Well, this is how you can do it. Apex is made through Java!

String jsonText = '{"Data": {"attributes": {"type": "Contact","url":"/services/data/v35.0/sobjects/Contact/0036100000JUXKkAAP"},"Id": "0036100000JUXKkAAP","Description": "","LastName": "Testing"}}';

Map<String, Object> cObjMap = (Map<String, Object>) JSON.deserializeUntyped(jsonText);
String cObjJson = JSON.serialize(cObjMap.get('Data'));
// Why again :(
Map<String, Object> cObjMapFurious = (Map<String, Object>) JSON.deserializeUntyped(cObjJson);
String cObjJsonDrunk = JSON.serialize(cObjMapFurious);
try
{
    SObject customObject = (SObject)JSON.deserialize(cObjJsonDrunk, Sobject.class);
    System.debug(' Accomplished: '+customObject);
}
catch(Exception ex)
{
    System.debug(' @@@@@ Don\'t visible '+ex.getMessage());
}