[SalesForce] Parsing JSON Values into List

Let me start by saying, I'm completely unfamiliar with json parsing. I have json that looks like this,

[  
   {  
      "locName":"Kansas"
   },
   {  
      "locName":"New York"
   },
   {  
      "locName":"Tokyo"
   },
   {  
      "locName":"Toronto"
   },
   {  
      "locName":"Des Moines"
   }
]

I just want to parse the names of the locations into a string list. How do I do it?
my code looks like:

while (parser.nextToken() != null) {
         if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&(parser.getText() == 'locName')) {
             myList.add(parser.getText());
             parser.nextToken();
          }
}

Best Answer

You can use json2apex to build a parser for you.

That said, here's the code you'd want to use:

public class Location {
    public String locName;
}

Later, when you want to parse your JSON:

List<Location> locations = (List<Location>)JSON.deserialize(myJsonString, List<Location>.class);

You'll get similar output from json2apex, but I just wrote this by hand.

If you want just the strings, you then just need to iterate:

String[] locationNames = new String[0];
for(Location item: locations) {
    locationNames.add(item.locName);
}
Related Topic