<問題・Problem>
JSON型の文字列をApex ClassでList型やMap型に変換したい!
JSON type String needs to be changed to List type or Map type in Apex Class!
<解決策・Solution>
JSON.deserializeとキャストを使用します。
Use
JSON.deserialize and Cast.
Listの場合/List case:
List<String> リスト名/List Name = (List<String>)JSON.deserialize(JSON文字列/JSON String , List<String>.class);
<サンプル・Sample>
JSON:
[
{"name":"pen","num":"10"},
{"name":"pineapple","num":"20"},
{"name":"apple","num":"30"}
]
Apex Class:
String jsonString = '[{"name":"pen","num":"10"},{"name":"pineapple","num":"20"},{"name":"apple","num":"30"}]';
List<map<String,String>> sampleList = (List<Map<String,String>>)JSON.deserialize(jsonString,List<Map<String,String>>.class);
for(Integer i = 0;i<sampleList.size();i++){
for(String s : sampleList[i].keySet()){
system.debug(s + ' : ' + sampleList[i].get(s));
}
}
Debug Result:
pen : 10
pineapple : 20
apple : 30