2

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();
          }
}
1
  • 1
    The serialize/deserialize methods of the JSON Class are generally all you will need and simpler to use than JSONParser.
    – Keith C
    Aug 18, 2016 at 22:47

1 Answer 1

8

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);
}
3
  • Man, sometimes I read a post, visualize the answer in my head, then you post it nearly verbatim. I guess that's a good sign. I almost posted this one from my phone since it's brief enough to get away with.
    – Adrian Larson
    Aug 18, 2016 at 22:46
  • 1
    SFDC doc on Json.serialize could be more useful. The example is pathetic (a scalar) and might not seem relevant to someone looking for a code sample resembling real world JSON input. It isn't until you read the round trip JSON serialize-deserialize that you see an example with collections and even then, if you are only trying to deserialize, you might skip reading the example.
    – cropredy
    Aug 18, 2016 at 23:13
  • 1
    @cropredy Yeah, someone should file a complaint with the documentation team.
    – sfdcfox
    Aug 18, 2016 at 23:19

You must log in to answer this question.

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