function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Charles Naughton 7Charles Naughton 7 

JSON parser is returning nullValue

I'm trying to parse JSON to extract a Zip Code from a JSON response. Instead of returning "10019-6018", the parser is returning "null10019-6019". Why is it inserting "null" in front of the value?

Here's the body of JSON response:
 
{"Addresses":[{"Address1":"787 7th Ave Fl 8th","Address2":"","City":"New 
York","State":"NY","Zip":"10019-018","IsResidential":"","DPV":"3"}],"IsCASS":true}

Here's a snippet of code showing what I'm doing with the parser:
 
HttpResponse response;
        response = h.send(req);
        System.debug(response.getBody());
        JSONParser parser = JSON.createParser(response.getBody());
        String resPostalCode;
        while(parser.nextToken() != null) {
            if((parser.getCurrentToken() == JSONToken.FIELD_NAME) && 
               (parser.getText() == 'Zip')) {
                   parser.nextToken();
                   resPostalCode += parser.getText();
            }
        }
        system.debug(resPostalCode);

 
J. Scott CromieJ. Scott Cromie
You will need to initialize your variable.  This gives the output you're looking for:

String strJSON = '{"Addresses":[{"Address1":"787 7th Ave Fl 8th","Address2":"","City":"New York","State":"NY","Zip":"10019-018","IsResidential":"","DPV":"3"}],"IsCASS":true}';
JSONParser parser = JSON.createParser(strJSON);
String resPostalCode = '';
  while(parser.nextToken() != null) {
    if((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&
       (parser.getText() == 'Zip')) {
          parser.nextToken();
          resPostalCode += parser.getText();
       }
  }
  system.debug(resPostalCode);