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 

Here's a snippet of code showing what I'm doing with the parser:

        HttpResponse response;
        response = h.send(req);
        JSONParser parser = JSON.createParser(response.getBody());
        String resPostalCode;
        while(parser.nextToken() != null) {
            if((parser.getCurrentToken() == JSONToken.FIELD_NAME) && 
               (parser.getText() == 'Zip')) {
                   resPostalCode += parser.getText();

1 Answer 1

    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
  • Holy wow! By using custom JSONResponse class, you are creating concrete addresses objects. Super!
    – Mahmood
    Commented Feb 24, 2017 at 22:35

You must log in to answer this question.

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