function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Tanner RussellTanner Russell 

How to deserialize a list of maps

I have created a list of maps and serialized it into a json string. What I would like to be a able to do is deserialize this string back into the same List of maps that was used to serialize it. Is this possible or is there a workaround I can perfom? thanks
//code
String json = JSON.serialize(masterList);
//test
List<Map<id,sObject> masterList = JSON.deserializeUntyped(json);
Best Answer chosen by Tanner Russell
Charisse de BelenCharisse de Belen
Hi Tanner,

Try this:
String jString = JSON.serialize(masterList);
List<Map<Id,sObject>> deserializedList = (List<Map<Id,sObject>>)JSON.deserialize(jString, List<Map<Id,sObject>>.class);

All Answers

karthikeyan perumalkarthikeyan perumal
Hello,

If you are looking to deserialize untyped without custom classes (so basically assume the data has the right structure at runtime) you can do it like this:

Example Code: 
 
Map<String, Object> meta = (Map<String, Object>) JSON.deserializeUntyped(JsonString);
List<Map<String, String>> myMaps = (List<Map<String, String>>) meta.get('results');
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_class_System_Json.htm#apex_System_Json_deserializeUntyped


Hope this will help you. 

Thanks
karthik

 
Tanner RussellTanner Russell
I am having an issue trying to deserialize the list I am getting the runtime exception 
System.TypeException: Invalid conversion from runtime type List<ANY> to Map<String,ANY>
(line 1 of your example)
Charisse de BelenCharisse de Belen
Hi Tanner,

Try this:
String jString = JSON.serialize(masterList);
List<Map<Id,sObject>> deserializedList = (List<Map<Id,sObject>>)JSON.deserialize(jString, List<Map<Id,sObject>>.class);
This was selected as the best answer
Tanner RussellTanner Russell
Yes that works thank you!