Tutorial

How to Parse US Addresses in Java / Spring Boot

Turn a freeform address string into clean, column-ready fields. Free API, the built-in HttpClient with Jackson records, and a clear map from every component to your database.

sthan.io Team
sthan.io Team
June 27, 2026 · 11 min read

You have a column called address full of freeform strings: "1600 Pennsylvania Ave NW Apt 4B, Washington DC 20500". It is fine for display, but useless for anything structured - you can't group by city, filter by ZIP, sort by street, or de-duplicate, because every part of the address is mashed into one field.

Address parsing fixes that. You send the raw string and get back discrete components: the primary number, the street name, the suffix, the directional, the unit, the city, the state, and the ZIP - each in its own field, ready to drop into its own column.

This tutorial shows you how to parse US addresses in Java using sthan.io's address API. We use the built-in java.net.http.HttpClient and Jackson, but the client is plain Java - it drops into a Spring Boot service, a CLI, a batch job, or a one-off data-migration task unchanged.

Quick summary: Send your API key as a Bearer token, call GET /v2/address-parser/usa/{address}, and read the components from the Result object - addressNumber, streetName, streetPostType, unitType, unitNumber, city, stateCode, zipCode. The free tier gives you 100 lookups/month - no credit card required.

What you'll need: Java 11 or later (Java 17 recommended) and a free sthan.io account. No credit card, no approval queue. The free parser tier is 100 lookups/month; paid plans start at $8/month if you need more.

Try it first

Parse any US address right here - no signup required:

Try it live

That's what you're building. Type a messy one-line address and the API hands back every component as a separate, standardized field.

What the API returns

Every response is wrapped in a standard envelope. For parsing, the Result field is a single object whose properties are the address components. This is a real response for 1600 Pennsylvania Ave NW Apt 4B:

{
  "Id": "2737f8f3-af83-4ba1-b9c3-e29d2ba9e03b",
  "Result": {
    "inputAddress": "1600 Pennsylvania Ave NW Apt 4B Washington DC 20500",
    "addressLine1": "1600 PENNSYLVANIA AVE NW",
    "addressLine2": null,
    "addressNumber": "1600",
    "streetPreDir": "",
    "streetName": "PENNSYLVANIA",
    "streetPostType": "AVE",
    "streetPostDir": "NW",
    "unitType": "apt",
    "unitNumber": "4b",
    "city": "WASHINGTON",
    "stateCode": "DC",
    "zipCode": "20500",
    "zip4": null,
    "county": null,
    "matchMode": "Speculative",
    "matchTier": "Near",
    "confidence": 0.7,
    "matchCode": {
      "houseNumber": "Matched",
      "street": "Matched",
      "unit": "Matched",
      "city": "Matched",
      "state": "Matched",
      "zipCode": "Matched",
      "zip4": "NotApplicable"
    },
    "footnotes": ["recovered: standardized via correction, not an exact match"]
  },
  "ClientSessionId": null,
  "StatusCode": 200,
  "IsError": false,
  "Errors": []
}
Casing matters in Java. The envelope keys (Id, Result, StatusCode, IsError, Errors) are PascalCase, while the component fields inside Result are camelCase (addressNumber, streetName, streetPostType). With Jackson, map the envelope's PascalCase keys explicitly with @JsonProperty("Result"), and let the camelCase component fields bind to natural Java field names. Add @JsonIgnoreProperties(ignoreUnknown = true) so extra fields never break deserialization.

The fields you'll use most often are covered in the component map below. Note that some fields are empty or null when they don't apply - there's no leading directional here, so streetPreDir is an empty string, and the parser didn't append a zip4 or county, so those are null.

Get your API key

  1. Sign up at sthan.io and subscribe to the free Address Parser tier
  2. Open your dashboard and create an API key
  3. Copy the key - it looks like sthan_live_xxxxxxxxxxxxxxxx

You get the key immediately, with no approval queue. An API key is the simplest way to authenticate: you send it as a Bearer token on every request and there is no separate login step. (If you prefer a short-lived token, there is a JWT flow covered later.)

Configure the project

The HTTP client is built into the JDK (java.net.http, Java 11+). Add Jackson for JSON, and keep your key out of source control by reading it from the environment:

# Maven — add Jackson to pom.xml
#   <dependency>
#     <groupId>com.fasterxml.jackson.core</groupId>
#     <artifactId>jackson-databind</artifactId>
#   </dependency>

# Set the key in your shell (or your run configuration / secrets manager)
export STHAN_API_KEY="sthan_live_xxxxxxxxxxxxxxxx"
Security tip: Never hard-code the key in a source file. Use an environment variable in production and a secrets manager or application.properties bound to an env var locally - and keep it out of version control. In Spring Boot, inject it with @Value("${sthan.api-key}").

Build the parser client

First, model the response as two records. The envelope keys are PascalCase, so map them with @JsonProperty; the component fields are camelCase and bind to natural field names:

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.List;

@JsonIgnoreProperties(ignoreUnknown = true)
public record SthanResponse(
        @JsonProperty("Id") String id,
        @JsonProperty("Result") ParsedAddress result,
        @JsonProperty("IsError") boolean isError,
        @JsonProperty("Errors") List<String> errors) {
}

@JsonIgnoreProperties(ignoreUnknown = true)
public record ParsedAddress(
        String inputAddress,
        String addressNumber,
        String streetPreDir,
        String streetName,
        String streetPostType,
        String streetPostDir,
        String unitType,
        String unitNumber,
        String city,
        String stateCode,
        String zipCode,
        String zip4) {
}

Now the client. Reuse one HttpClient and one ObjectMapper across calls - both are thread-safe and designed to be shared. It URL-encodes the address, calls the endpoint, unwraps the envelope, and returns the ParsedAddress:

import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;

public class ParserClient {

    private static final String BASE_URL = "https://api.sthan.io";
    private static final String API_KEY = System.getenv("STHAN_API_KEY");

    private final HttpClient http = HttpClient.newHttpClient();
    private final ObjectMapper mapper = new ObjectMapper();

    public ParsedAddress parse(String address, String mode) throws Exception {
        // URLEncoder uses '+' for spaces; a path segment needs %20
        String encoded = URLEncoder.encode(address.strip(), StandardCharsets.UTF_8)
                .replace("+", "%20");
        URI uri = URI.create(
                BASE_URL + "/v2/address-parser/usa/" + encoded + "?match=" + mode);

        HttpRequest request = HttpRequest.newBuilder(uri)
                .header("Authorization", "Bearer " + API_KEY)
                .GET()
                .build();

        HttpResponse<String> response =
                http.send(request, HttpResponse.BodyHandlers.ofString());
        if (response.statusCode() >= 400) {
            throw new RuntimeException("Parser HTTP " + response.statusCode());
        }

        SthanResponse envelope = mapper.readValue(response.body(), SthanResponse.class);
        if (envelope.isError()) {
            throw new RuntimeException(
                    "Parser error: " + String.join(", ", envelope.errors()));
        }
        return envelope.result();
    }
}

That's the whole integration. One call:

ParsedAddress result = new ParserClient()
        .parse("1600 pennsylvania ave nw apt 4b washington dc 20500", "speculative");

System.out.println(result.addressNumber());                       // 1600
System.out.println(result.streetName());                          // PENNSYLVANIA
System.out.println(result.streetPostType());                      // AVE
System.out.println(result.unitType() + " " + result.unitNumber()); // apt 4b
System.out.println(result.city() + " " + result.stateCode() + " " + result.zipCode());
Why reuse the HttpClient? An HttpClient owns a connection pool and an executor; creating one per call is wasteful and can exhaust resources under load. Build it once (a singleton, or a Spring @Bean) and share it. The same goes for ObjectMapper - construct it once and reuse it.

Choose a match mode

The match parameter controls how much typo tolerance the parser applies while standardizing components. The same call supports four modes, from strictest to loosest:

ModeBehaviorUse when
strict Only confident, exact-component matches; returns little or nothing when the input is ambiguous. You only want components you can fully trust.
balanced Exact plus typo-corrected components. Returns the best parse, flagging corrected fields. Typical cleanup of user-entered addresses.
fuzzy Wider recovery for messy or partial input. Higher recall, more corrections. Backfilling a column of inconsistent legacy data.
speculative Loosest recovery, with extra tolerance for heavily misspelled street names. Best-effort parses are flagged matchTier = "Speculative". Maximum recovery / agent tooling. This is the default.

If you omit match, the endpoint defaults to speculative for the widest recovery. Whichever mode you pick, the location-defining parts of the address - the primary number, ordinal, directional, state, and the street's core name - are never substituted. A looser mode only widens tolerance for misspellings of the same street.

Map the components to your fields

Each component comes back as its own field, so mapping them to database columns is a direct copy. The fields you'll use most:

FieldMeaningExample
addressNumberPrimary (house/building) number1600
streetPreDirLeading directionalN in "N Main St"
streetNameCore street namePENNSYLVANIA
streetPostTypeStreet suffix / typeAVE, ST, BLVD
streetPostDirTrailing directionalNW
unitType / unitNumberSecondary unit designator and valueapt / 4b
city, stateCode, zipCode, zip4City, two-letter state, 5-digit ZIP, +4WASHINGTON, DC, 20500

A few more components cover edge cases: streetPreType, streetPreMod, streetPreSep, and streetPostMod capture pre/post modifiers in unusual street names (for example "Avenue of the Americas"). They're empty for ordinary addresses. Pair the parse with matchCode - a per-component breakdown (Matched / Corrected / Inferred / Unmatched / NotApplicable) - so you can tell which fields were trusted as-is versus corrected. Here is a parse going straight into a persistence entity:

ParsedAddress result = client.parse(rawAddress, "speculative");

// Map straight into your JPA entity (or a PreparedStatement) —
// one column per component
AddressEntity entity = new AddressEntity();
entity.setAddressNumber(result.addressNumber());
entity.setStreetPreDir(result.streetPreDir());
entity.setStreetName(result.streetName());
entity.setStreetType(result.streetPostType());
entity.setStreetPostDir(result.streetPostDir());
entity.setUnitType(result.unitType());
entity.setUnitNumber(result.unitNumber());
entity.setCity(result.city());
entity.setState(result.stateCode());
entity.setZipCode(result.zipCode());
entity.setZip4(result.zip4());
addressRepository.save(entity);

Alternative: JWT authentication

An API key is the simplest option and is all most apps need. If your security policy prefers short-lived credentials, the platform also supports a 2-step JWT flow. You call GET /Auth/Token once with your profileName and profilePassword headers, receive a token valid for up to 60 minutes, then send that token as the Bearer value on subsequent calls:

@JsonIgnoreProperties(ignoreUnknown = true)
record TokenEnvelope(@JsonProperty("Result") TokenResult result) {}

@JsonIgnoreProperties(ignoreUnknown = true)
record TokenResult(@JsonProperty("access_token") String accessToken) {}

public String getToken() throws Exception {
    HttpRequest request = HttpRequest.newBuilder(URI.create(BASE_URL + "/Auth/Token"))
            .header("profileName", System.getenv("STHAN_PROFILE_NAME"))
            .header("profilePassword", System.getenv("STHAN_PROFILE_PASSWORD"))
            .GET()
            .build();

    HttpResponse<String> response =
            http.send(request, HttpResponse.BodyHandlers.ofString());
    TokenEnvelope env = mapper.readValue(response.body(), TokenEnvelope.class);
    return env.result().accessToken();
}

You would then set Authorization: Bearer <token> per request with the cached token instead of a static key. Everything else - the endpoint, the envelope, the parsing - stays exactly the same. Cache the token and refresh it shortly before the 60-minute expiry.

Handle errors

Two status codes are worth handling explicitly so a hiccup never stalls a batch job:

  • 401 - The key or token was rejected. Check the value and, on the JWT flow, refresh and retry once.
  • 429 - Rate limit reached. Back off and retry rather than dropping the row.
public ParsedAddress parseWithRetry(String address, String mode, int retries)
        throws Exception {
    for (int attempt = 0; ; attempt++) {
        try {
            return parse(address, mode);
        } catch (RuntimeException ex) {
            boolean rateLimited = ex.getMessage() != null
                    && ex.getMessage().contains("429");
            if (rateLimited && attempt < retries) {
                Thread.sleep(1000L * (1L << attempt)); // 1s, then 2s
                continue;
            }
            throw ex;
        }
    }
}

The exponential back-off (1s, then 2s) is enough for transient limits. For a large backfill, add a small delay between rows and a circuit breaker so one bad minute doesn't stall the whole queue.

What's next: confirm the parsed address is deliverable

Parsing gives you clean, structured components fast. It does not, on its own, confirm that mail or a package will actually arrive - a well-formed address can still point at a unit that no longer accepts delivery. When deliverability matters, run the address through the Address Verification API, which returns a deliverability status and appends ZIP+4 and county. It's the same envelope and the same HttpClient pattern - one GET against /v2/address-verification/usa/{address}. The Java walkthrough is here: Verify US Addresses in Java.

If you want users to enter a clean address in the first place, Address Autocomplete suggests complete addresses as they type. For the full Java walkthrough covering parsing, verification, and geocoding together, see Integrate Address APIs in Java.

Frequently Asked Questions

Send your sthan.io API key as a Bearer token and call GET /v2/address-parser/usa/{address} with java.net.http.HttpClient. Deserialize the Result object with Jackson and read the components - addressNumber, streetName, streetPostType, unitType, unitNumber, city, stateCode, and zipCode. The full working client is in the sections above.

The free tier includes 100 lookups per month with no credit card required. Paid plans start at $8/month. There is no trial period; the free tier is permanent. See pricing for higher-volume plans.

The parser breaks a freeform address into discrete fields: addressNumber, streetPreDir and streetPostDir (leading and trailing directionals), streetName, streetPostType (the suffix like Ave or St), unitType and unitNumber, city, stateCode, zipCode, and zip4. Each field is returned separately so you can store it in its own column.

Parsing splits a freeform address into structured components and standardizes their format. Verification goes a step further and confirms the address is real and deliverable, returning a deliverability status. Parse when you need clean, column-ready fields; verify when you need to know whether mail or a package will actually arrive. See Verify US Addresses in Java.

Call it from your Java backend, not the browser. The API does not enable CORS for browser requests, and putting your API key in client-side JavaScript would expose it to anyone viewing the page source. Parse server-side, then return the structured fields to the page.

Turn messy address strings into clean fields

Parse freeform addresses into structured components with one call - free tier of 100 lookups/month, paid from $8/month, no credit card to start.

sthan.io Team
Written by sthan.io Team

The sthan.io engineering team builds and maintains address verification, parsing, geocoding, and autocomplete APIs. With deep expertise in postal addressing standards and spatial data systems, we help businesses improve address data quality and reduce failed deliveries. Questions? Reach us at [email protected].

Learn more about us