0

Sorry for this noob question but I just want to ask:

String stringJSON = '[{"action":"ASSIGN","value":"Router"},{"action":"DISABLE","value":true},{"action":"HIDE","value":false}]';

Can anyone help how do I convert this JSON string into List of Map?

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.

Sorry if my explanation is unclear but I hope you get my point. Thank you in advance!

2 Answers 2

0

I'm Not sure if this is the best way, but you can start from here:

String stringJSON = '[{"action":"ASSIGN","value":"Router"},{"action":"DISABLE","value":true},{"action":"HIDE","value":false}]';

List<Object> listOfAny = (List<Object>) JSON.deserializeUntyped(stringJSON);
List<Map<String, Object>> listMap = new List<Map<String, Object>>();

for(Object obj : listOfAny) {
    Map<String, Object> mapObj = (Map<String, Object>) obj;
    
    listMap.add(mapObj);
}

System.debug(listMap);

// Example: Get the two maps 'action' and 'value' from the list index 1
System.debug(listMap[1].get('action'));
System.debug(listMap[1].get('value'));

Hope it helps!

0

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<String, String> valueByAction = new Map<String, String>();
for(Wrapper w : (List<Wrapper> )JSON.deserialize(stringJSON, List<Wrapper>.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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .