0

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);
5
    String resPostalCode;

Since your string is null, += causes the code to expand to:

resPostalCode = null + '10019-6019';

Instead, make sure your string isn't null first:

Sring resPostalCode = '';

You can void silly mistakes like this by using the more reliable JSON.deserialize method instead.

public class Address {
    public String Address1, Address2, City, State, Zip, DPV;
    public Boolean IsResidential;
}
public class JSONResponse {
    public Address[] Addresses;
    public Boolean IsCASS;
}

...

JSONResponse data = (JSONResponse)JSON.deserialize(res.getBody(), JSONResponse.class);
for(Address addr: data.Addresses) {
    // addr is an Address
}
| improve this answer | |
  • Holy wow! By using custom JSONResponse class, you are creating concrete addresses objects. Super! – Mahmood Feb 24 '17 at 22:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.