How can I convert a json array of strings into a list of maps?

270    Asked by ClareMatthews in Salesforce , Asked on Apr 19, 2023
String stringJSON = '[{"action":"ASSIGN","value":"Router"},{"action":"DISABLE","value":true},{"action":"HIDE","value":false}]';

Can anyone help me convert this JSON string into a List of Maps?

So the expected outcome is List.size() is 3 where each value is mapped so that I can get the Action and the Value?

  • List value 1 = 2 maps. The one is Action=ASSIGN and the other one is Value=Router.
    List value 2 = 2 maps again. The one is Action=DISABLE and the other one is Value=TRUE.
    List value 3 = 2 maps again. The one is Action=HIDE and the other one is Value=FALSE.
Answered by Ranjana Admin

To convert a json array of strings into a list of maps, create a wrapper class as per json structure.

  public class Wrapper { public String action; public String value; }

Map json to wrapper and create map.

  String stringJSON = '[{"action":"ASSIGN","value":"Router"},{"action":"DISABLE","value":true},{"action":"HIDE","value":false}]'; Map valueByAction = new Map(); for(Wrapper w : (List )JSON.deserialize(stringJSON, List.class)) { valueByAction.put(w.action, w.value); } System.debug('ASSIGN : '+valueByAction.get('ASSIGN')); //output Router System.debug('DISABLE : '+valueByAction.get('DISABLE')); //output true System.debug('HIDE : '+valueByAction.get('HIDE')); //output false


Your Answer

Interviews

Parent Categories