3

I wonder if it is possible to JSON.deserializeUntyped directly to DateTime type. How can I check if deserialized Object in Map has type of DateTime? I am curious is it possible, because Object in map has always String type.

String myDate = '{ "MyDate" : "2018-08-31T06:00:00.000Z" }';
Map<String, Object> ds = (Map<String, Object>) 
JSON.deserializeUntyped(myDate);
System.debug(ds.get('MyDate') instanceof DateTime);
System.debug(JSON.deserialize((String)ds.get('MyDate'), DateTime.class));

enter image description here

3

Your format doesn't line up with those that work with Datetime.valueOf (nor Datetime.parse). The format it expects is 2018-08-31 06:00:00 I was able to do some light string manipulation to get the Datetime value:

String myDate = '{"MyDate": "2018-08-31T06:00:00.000Z"}';
Map<String, Object> data = (Map<String, Object>)JSON.deserializeUntyped(myDate);
String formatted = ((String)data.get('MyDate')).replace('T', ' ').replace('.000Z', '');
Datetime value = Datetime.valueOfGmt(formatted));
| improve this answer | |
3

No, deserializedUntyped simply doesn't work that way; it can only deserialize to List<Object>, Map<String, Object>, Decimal, String, Boolean and null. It doesn't try to figure out if there's a Date or a DateTime or a more complicated structure. However, assuming you have your value, you can parse it independently:

Map<String, Object> values = (Map<String, Object>)JSON.deserializeUntyped(myDate);
String value = (String)values.get('MyDate');
DateTime dt = (DateTime)JSON.deserialize('"'+value+'"', DateTime.class);

I realize it's not terribly practical, but that's the only way you'd get the JSON parser to work the way you'd like. It'd be far more practical to JSON.deserialize to a concrete data type:

Map<String, DateTime> values = (Map<String, DateTime>)
  JSON.deserialize(myDate, Map<String, DateTime>.class);

Or, as Adrian suggested, removing the parts that DateTime.valueOf/DateTime.parse don't like, and using that instead.

| improve this answer | |

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.